<commit_before>/*
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Id$
 */
package org.gridlab.gridsphere.services.core.registry.impl;

import org.gridlab.gridsphere.portlet.PortletException;
import org.gridlab.gridsphere.portlet.PortletLog;
import org.gridlab.gridsphere.portlet.PortletRequest;
import org.gridlab.gridsphere.portlet.PortletResponse;
import org.gridlab.gridsphere.portlet.impl.SportletLog;
import org.gridlab.gridsphere.portlet.service.PortletServiceUnavailableException;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceConfig;
import org.gridlab.gridsphere.portletcontainer.*;
import org.gridlab.gridsphere.portletcontainer.impl.PortletWebApplicationImpl;
import org.gridlab.gridsphere.services.core.registry.PortletManagerService;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.File;
import java.util.*;

/**
 * The <code>PortletManager</code> is a singleton responsible for maintaining the registry of portlet
 * web applications known to the portlet container.
 */
public class PortletManager implements PortletManagerService {

    private final static String CORE_CONTEXT = "startup-portlet-webapps";
    private static PortletLog log = SportletLog.getInstance(PortletManager.class);
    private static PortletManager instance = new PortletManager();
    private ServletContext context = null;
    private boolean isInitialized = false;
    private PortletRegistry registry = PortletRegistry.getInstance();

    // A multi-valued hashtable with a webapp key and a List value containing portletAppID's
    private List webapps = new Vector();

    /**
     * Default instantiation disallowed
     */
    private PortletManager() {}


    private static class WebappComparator implements Comparator {

        public int compare(Object webapp1, Object webapp2) {

            if (!(webapp1 instanceof String) || !(webapp2 instanceof String)) {
                throw new ClassCastException("Can only compare string webapp names!!");
            }
            String _webapp1 = (String)webapp1;
            String _webapp2 = (String)webapp2;

            int a = _webapp1.lastIndexOf(".");

            int b = _webapp2.lastIndexOf(".");

            // check if a has a priority and b does not
            if ((a > 0) && (b < 0)) {
                return 1;
            }
            // check if b has a priority and a does not
            if ((a < 0) && (b > 0)) {
                return -1;
            }
            // check if a and b do not have a priority then use alphabetical
            if ((a > 0) && (b > 0)) {

                try {
                    int a1 = Integer.valueOf(_webapp1.substring(a+1)).intValue();
                    int a2 = Integer.valueOf(_webapp2.substring(b+1)).intValue();
                    if (a1 > a2) return 1;
                    if (a1 < a2) return -1;
                    if (a1 == a2) return 0;
                } catch (NumberFormatException e) {
                    // oh well
                }
            }

            // use alphabetical comparison
            return _webapp1.compareTo(_webapp2);

        }

    }

    /**
     * Return an instance of PortletManager
     *
     * @return the PortletManager instance
     */
    public static PortletManager getInstance() {
        return instance;
    }

    /**
     * Initializes portlet web applications that are defined by the <code>PortletManagerService</code>
     *
     * @param config the <code>PortletServiceConfig</code>
     * @throws PortletServiceUnavailableException if initialization fails
     */
    public synchronized void init(PortletServiceConfig config) throws PortletServiceUnavailableException {
        log.debug("in init()");
        if (!isInitialized) {
            context = config.getServletContext();
            //String webapps = config.getInitParameter(CORE_CONTEXT);

            String portletsPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/Portlets");
            File f = new File(portletsPath);
            if (f.exists() && f.isDirectory()) {
                String[] webappFiles = f.list();

                // sort webapps by priority
                Arrays.sort(webappFiles, new WebappComparator());

                // get rid of any priority numbers
                String webapp = "";
                int idx = 0;
                for (int i = 0; i < webappFiles.length; i++) {
                    webapp = webappFiles[i];
                    if ((idx = webapp.lastIndexOf(".")) > 0) {
                        webappFiles[i] = webapp.substring(0, idx);
                    }
                }

                if (webappFiles != null) {
                    for (int i = 0; i < webappFiles.length; i++) {
                        try {
                            webapp = webappFiles[i];
                            PortletWebApplication portletWebApp = new PortletWebApplicationImpl(webapp, context);
                            addWebApp(portletWebApp);
                        } catch (PortletException e) {
                            log.error("Unable to create portlet web application: " + webapp);
                        }
                    }          
                }
            } else {
                log.error(portletsPath + " does not exist!");
            }
            isInitialized = true;
        }
    }

    /**
     * Adds a portlet web application to the registry
     *
     * @param portletWebApp the portlet web application name
     */
    public synchronized void addWebApp(PortletWebApplication portletWebApp) {
        log.debug("adding webapp: " + portletWebApp.getWebApplicationName());
        addPortletFile(portletWebApp.getWebApplicationName());
        Collection appPortlets = portletWebApp.getAllApplicationPortlets();
        Iterator it = appPortlets.iterator();
        while (it.hasNext()) {
            ApplicationPortlet appPortlet = (ApplicationPortlet) it.next();
            log.debug("Adding application portlet: " + appPortlet.getApplicationPortletID());
            registry.addApplicationPortlet(appPortlet);
        }
        webapps.add(portletWebApp);
    }

    private void addPortletFile(String webappName) {
        String portletsPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/Portlets");
        File newfile = new File(portletsPath + File.separator + webappName);
        try {
            newfile.createNewFile();
        } catch (IOException e) {
            log.error("Unable to create portlet app file: " + newfile.getAbsolutePath());
        }
    }

    private void removePortletFile(String webappName) {
        String portletsPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/Portlets");
        File newfile = new File(portletsPath + File.separator + webappName);
        if (newfile.exists()) {
            newfile.delete();
        }
    }

    /**
     * Removes the portlet application
     *
     * @param webApplicationName the portlet application name
     */
    protected synchronized void removePortletWebApplication(String webApplicationName) {
        log.debug("in removePortletWebApplication: " + webApplicationName);
        Iterator it = webapps.iterator();
        List removeWebApps = new ArrayList();
        while (it.hasNext()) {
            PortletWebApplication webApp = (PortletWebApplication)it.next();

            if (webApp.getWebApplicationName().equalsIgnoreCase(webApplicationName)) {
                webApp.destroy();<commit_msg>committed fix to adding/removing portlet webapp file as necessary<commit_after>/*
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Id$
 */
package org.gridlab.gridsphere.services.core.registry.impl;

import org.gridlab.gridsphere.portlet.PortletException;
import org.gridlab.gridsphere.portlet.PortletLog;
import org.gridlab.gridsphere.portlet.PortletRequest;
import org.gridlab.gridsphere.portlet.PortletResponse;
import org.gridlab.gridsphere.portlet.impl.SportletLog;
import org.gridlab.gridsphere.portlet.service.PortletServiceUnavailableException;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceConfig;
import org.gridlab.gridsphere.portletcontainer.*;
import org.gridlab.gridsphere.portletcontainer.impl.PortletWebApplicationImpl;
import org.gridlab.gridsphere.services.core.registry.PortletManagerService;

import javax.servlet.ServletContext;
import java.io.IOException;
import java.io.File;
import java.util.*;

/**
 * The <code>PortletManager</code> is a singleton responsible for maintaining the registry of portlet
 * web applications known to the portlet container.
 */
public class PortletManager implements PortletManagerService {

    private final static String CORE_CONTEXT = "startup-portlet-webapps";
    private static PortletLog log = SportletLog.getInstance(PortletManager.class);
    private static PortletManager instance = new PortletManager();
    private ServletContext context = null;
    private boolean isInitialized = false;
    private PortletRegistry registry = PortletRegistry.getInstance();

    // A multi-valued hashtable with a webapp key and a List value containing portletAppID's
    private List webapps = new Vector();

    /**
     * Default instantiation disallowed
     */
    private PortletManager() {}


    private static class WebappComparator implements Comparator {

        public int compare(Object webapp1, Object webapp2) {

            if (!(webapp1 instanceof String) || !(webapp2 instanceof String)) {
                throw new ClassCastException("Can only compare string webapp names!!");
            }
            String _webapp1 = (String)webapp1;
            String _webapp2 = (String)webapp2;

            int a = _webapp1.lastIndexOf(".");

            int b = _webapp2.lastIndexOf(".");

            // check if a has a priority and b does not
            if ((a > 0) && (b < 0)) {
                return 1;
            }
            // check if b has a priority and a does not
            if ((a < 0) && (b > 0)) {
                return -1;
            }
            // check if a and b do not have a priority then use alphabetical
            if ((a > 0) && (b > 0)) {

                try {
                    int a1 = Integer.valueOf(_webapp1.substring(a+1)).intValue();
                    int a2 = Integer.valueOf(_webapp2.substring(b+1)).intValue();
                    if (a1 > a2) return 1;
                    if (a1 < a2) return -1;
                    if (a1 == a2) return 0;
                } catch (NumberFormatException e) {
                    // oh well
                }
            }

            // use alphabetical comparison
            return _webapp1.compareTo(_webapp2);

        }

    }

    /**
     * Return an instance of PortletManager
     *
     * @return the PortletManager instance
     */
    public static PortletManager getInstance() {
        return instance;
    }

    /**
     * Initializes portlet web applications that are defined by the <code>PortletManagerService</code>
     *
     * @param config the <code>PortletServiceConfig</code>
     * @throws PortletServiceUnavailableException if initialization fails
     */
    public synchronized void init(PortletServiceConfig config) throws PortletServiceUnavailableException {
        log.debug("in init()");
        if (!isInitialized) {
            context = config.getServletContext();
            //String webapps = config.getInitParameter(CORE_CONTEXT);

            String portletsPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/Portlets");
            File f = new File(portletsPath);
            if (f.exists() && f.isDirectory()) {
                String[] webappFiles = f.list();

                // sort webapps by priority
                Arrays.sort(webappFiles, new WebappComparator());

                // get rid of any priority numbers
                String webapp = "";
                int idx = 0;
                for (int i = 0; i < webappFiles.length; i++) {
                    webapp = webappFiles[i];
                    if ((idx = webapp.lastIndexOf(".")) > 0) {
                        webappFiles[i] = webapp.substring(0, idx);
                    }
                }

                if (webappFiles != null) {
                    for (int i = 0; i < webappFiles.length; i++) {
                        try {
                            webapp = webappFiles[i];
                            PortletWebApplication portletWebApp = new PortletWebApplicationImpl(webapp, context);
                            addWebApp(portletWebApp);
                        } catch (PortletException e) {
                            log.error("Unable to create portlet web application: " + webapp);
                        }
                    }          
                }
            } else {
                log.error(portletsPath + " does not exist!");
            }
            isInitialized = true;
        }
    }

    /**
     * Adds a portlet web application to the registry
     *
     * @param portletWebApp the portlet web application name
     */
    public synchronized void addWebApp(PortletWebApplication portletWebApp) {
        log.debug("adding webapp: " + portletWebApp.getWebApplicationName());
        addPortletFile(portletWebApp.getWebApplicationName());
        Collection appPortlets = portletWebApp.getAllApplicationPortlets();
        Iterator it = appPortlets.iterator();
        while (it.hasNext()) {
            ApplicationPortlet appPortlet = (ApplicationPortlet) it.next();
            log.debug("Adding application portlet: " + appPortlet.getApplicationPortletID());
            registry.addApplicationPortlet(appPortlet);
        }
        webapps.add(portletWebApp);
    }

    private void addPortletFile(String webappName) {
        String portletsPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/Portlets");

        File f = new File(portletsPath);
        if (f.exists() && f.isDirectory()) {
            String[] webappFiles = f.list();
            for (int i = 0; i < webappFiles.length; i++) {
                if (webappFiles[i].startsWith(webappName) || webappName.startsWith(webappFiles[i])) return;
            }
        }
        File newfile = new File(portletsPath + File.separator + webappName);
        try {
            newfile.createNewFile();
        } catch (IOException e) {
            log.error("Unable to create portlet app file: " + newfile.getAbsolutePath());
        }
    }

    private void removePortletFile(String webappName) {
        String portletsPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/Portlets");
        File f = new File(portletsPath);
        if (f.exists() && f.isDirectory()) {
            String[] webappFiles = f.list();
            for (int i = 0; i < webappFiles.length; i++) {
                if (webappFiles[i].startsWith(webappName) || webappName.startsWith(webappFiles[i])) {
                    File newfile = new File(portletsPath + File.separator + webappFiles[i]);
                    newfile.delete();
                }
            }
        }
    }

    /**
     * Removes the portlet application
     *
     * @param webApplicationName the portlet application name
     */
    protected synchronized void removePortletWebApplication(String webApplicationName) {
        log.debug("in removePortletWebApplication: " + webApplicationName);
        Iterator it = webapps.iterator();
        List removeWebApps = new ArrayList();
        while (it.hasNext()) {
            PortletWebApplication webApp = (PortletWebApplication)it.next();

            if (webApp.getWebApplicationName().equalsIgnoreCase(webApplicationName)) {
                webApp.destroy();
{'fraction_non_alphanumeric': 0.09821371813616427, 'fraction_numerical': 0.005212637467421016, 'mean_word_length': 2.1257699185376513, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '2145880', 'n_tokens_mistral': 4254, 'n_tokens_neox': 4071, 'n_words': 1014}