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

import org.gridlab.gridsphere.core.persistence.PersistenceManagerException;
import org.gridlab.gridsphere.portlet.*;
import org.gridlab.gridsphere.portlet.impl.SportletLog;
import org.gridlab.gridsphere.portlet.service.PortletService;
import org.gridlab.gridsphere.portlet.service.PortletServiceNotFoundException;
import org.gridlab.gridsphere.portlet.service.PortletServiceUnavailableException;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceAuthorizer;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceConfig;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceFactory;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceProvider;
import org.gridlab.gridsphere.portlet.service.spi.impl.descriptor.SportletServiceCollection;
import org.gridlab.gridsphere.portlet.service.spi.impl.descriptor.SportletServiceDefinition;
import org.gridlab.gridsphere.portlet.service.spi.impl.descriptor.SportletServiceDescriptor;
import org.gridlab.gridsphere.portletcontainer.GridSphereConfig;
import org.gridlab.gridsphere.portletcontainer.PortletSessionManager;
import org.gridlab.gridsphere.services.core.security.acl.impl.AccessControlManager;
import org.gridlab.gridsphere.services.core.user.UserSessionManager;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.*;

/**
 * The <code>SportletServiceFactory</code> provides a factory for the creation
 * of portlet services. The <code>SportletServiceFactory</code> is also
 * responsible for portlet service lifecycle management including
 * initialization and shutdown.
 */
public class SportletServiceFactory implements PortletServiceFactory, PortletSessionListener {

    private static PortletLog log = SportletLog.getInstance(SportletServiceFactory.class);
    private static SportletServiceFactory instance = null;
    private static AccessControlManager aclManager = AccessControlManager.getInstance();
    private static PortletSessionManager portletSessionManager = PortletSessionManager.getInstance();
    private static UserSessionManager userSessionManager = UserSessionManager.getInstance();


    // Maintain a single copy of each service instantiated
    // as a classname and PortletServiceProvider pair
    private static Hashtable initServices = new Hashtable();

    // Hash of all services key = service interface name, value = SportletServiceDefinition
    private static Hashtable allServices = new Hashtable();

    // Hash of all user services
    private static Hashtable userServices = new Hashtable();

    // Hash of all user services
    private static Hashtable serviceContexts = new Hashtable();


    /**
     * Private constructor. Use getDefault() instead.
     */
    private SportletServiceFactory() {
        // Reads in the service definitions from the xml file and stores them in allServices
        // organized according to service interface keys and service definition values
        String servicesPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/PortletMaster.xml");
        String servicesMappingPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/mapping/portlet-services-mapping.xml");
        addServices(GridSphereConfig.getServletContext(), servicesPath, servicesMappingPath);
    }

    public void login(PortletRequest req) throws PortletException {

    }

    public void logout(PortletSession session) throws PortletException {
        log.debug("in logout of SportletServiceFactory");
        String userid = userSessionManager.getUserIdFromSession(session);
        if ((userid != null) && (userServices.containsKey(userid))) {
            log.debug("Removing services for userid: " + userid);
            Map servs = (Map)userServices.get(userid);
            Collection c = servs.values();
            Iterator it = c.iterator();
            while (it.hasNext()) {
                PortletServiceProvider psp = (PortletServiceProvider)it.next();
                psp.destroy();
                psp = null;
            }
            userServices.remove(userid);
        }
    }

    /**
     * Umarshalls services from the descriptor file found in servicesPath
     * using the mapping file specified
     *
     * @param servicesPath the path to the portlet services descriptor file
     * @param mappingPath the path to the portlet services mapping file
     */
    public synchronized void addServices(ServletContext ctx, String servicesPath, String mappingPath) {
        SportletServiceDescriptor descriptor = null;
        try {
            descriptor = new SportletServiceDescriptor(servicesPath, mappingPath);
        } catch (IOException e) {
            log.error("IO error unmarshalling " + servicesPath + " using " + mappingPath + " : " + e.getMessage());
            return;
        } catch (PersistenceManagerException e) {
            log.error("Unable to unmarshall " + servicesPath + " using " + mappingPath + " : " + e.getMessage());
            return;
        }
        SportletServiceCollection serviceCollection = descriptor.getServiceCollection();
        List services = serviceCollection.getPortletServicesList();
        Iterator it = services.iterator();
        while (it.hasNext()) {
            SportletServiceDefinition serviceDef = (SportletServiceDefinition) it.next();
            allServices.put(serviceDef.getServiceInterface(), serviceDef);
            log.debug("adding service: " + serviceDef.getServiceInterface() + " service def: " + serviceDef.toString());
            serviceContexts.put(serviceDef.getServiceInterface(), ctx);
        }
    }

    public static synchronized SportletServiceFactory getInstance() {
        if (instance == null) {
            instance = new SportletServiceFactory();
        }
        return instance;
    }

    /**
     * createPortletServiceFactory instantiates the given class and initializes it. The portlet service properties
     * file must be specified in the ServletContext as an InitParameter with the "PortletServices.properties" key.
     * If no properties file is found or any error occurs an exception is thrown.
     *
     * @param service the class of the service
     * @param servletContext the servlet configuration
     * @return the instantiated portlet service
     * @throws PortletServiceUnavailableException if the portlet service is unavailable
     * @throws PortletServiceNotFoundException if the PortletService is not found
     */
    public PortletService createPortletService(Class service,
                                               ServletContext servletContext,
                                               boolean useCachedService)
            throws PortletServiceUnavailableException, PortletServiceNotFoundException {

        PortletServiceProvider psp = null;

        // see if we already have an instance of this service
        if (service == null) {
            throw new PortletServiceUnavailableException("Received null service class");
        }

        String serviceName = service.getName();
        // if init'ed service exists then use it
        if (useCachedService) {
            psp = (PortletServiceProvider) initServices.get(serviceName);
            if (psp != null) return psp;
        }

        SportletServiceDefinition def = (SportletServiceDefinition) allServices.get(serviceName);
        if (def == null) {
            log.error("Unable to find portlet service interface: " + serviceName +
                    " . Please check PortletServices.xml file for proper service entry");
            throw new PortletServiceNotFoundException("Unable to find portlet service: " + serviceName);
        }

        // if user is required then pass in Guest user privileges
        if (def.getUserRequired()) {
            return createUserPortletService(service, GuestUser.getInstance(), servletContext, useCachedService);
        }

        /* Create the service implementation */
        String serviceImpl = def.getServiceImplementation();
        if (serviceImpl == null) {
            log.error("Unable to find implementing portlet service: " + serviceName +
                    " . Please check PortletServices.xml file for proper service entry");
            throw new PortletServiceNotFoundException("Unable to find implementing portlet service for interface: " + serviceName);
        }

        Properties configProperties = def.getConfigProperties();

        ServletContext ctx = (ServletContext)serviceContexts.get(serviceName);
        PortletServiceConfig portletServiceConfig =
                new SportletServiceConfig(service, configProperties, ctx);

        try {
            psp = (PortletServiceProvider) Class.forName(serviceImpl).newInstance();
        } catch (Exception e) {
            log.error("Unable to create portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to create portlet service: " + serviceImpl, e);
        }

        try {
            psp.init(portletServiceConfig);
        } catch (PortletServiceUnavailableException e) {
            log.error("Unable to initialize portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to initialize portlet service: " + serviceImpl, e);
        }

        initServices.put(serviceName, psp);
        return psp;
    }<commit_msg>Added more error log to determine the reason why a portlet service cannot be created.<commit_after>/*
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 * @version $Id$
 */
package org.gridlab.gridsphere.portlet.service.spi.impl;

import org.gridlab.gridsphere.core.persistence.PersistenceManagerException;
import org.gridlab.gridsphere.portlet.*;
import org.gridlab.gridsphere.portlet.impl.SportletLog;
import org.gridlab.gridsphere.portlet.service.PortletService;
import org.gridlab.gridsphere.portlet.service.PortletServiceNotFoundException;
import org.gridlab.gridsphere.portlet.service.PortletServiceUnavailableException;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceAuthorizer;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceConfig;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceFactory;
import org.gridlab.gridsphere.portlet.service.spi.PortletServiceProvider;
import org.gridlab.gridsphere.portlet.service.spi.impl.descriptor.SportletServiceCollection;
import org.gridlab.gridsphere.portlet.service.spi.impl.descriptor.SportletServiceDefinition;
import org.gridlab.gridsphere.portlet.service.spi.impl.descriptor.SportletServiceDescriptor;
import org.gridlab.gridsphere.portletcontainer.GridSphereConfig;
import org.gridlab.gridsphere.portletcontainer.PortletSessionManager;
import org.gridlab.gridsphere.services.core.security.acl.impl.AccessControlManager;
import org.gridlab.gridsphere.services.core.user.UserSessionManager;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.*;

/**
 * The <code>SportletServiceFactory</code> provides a factory for the creation
 * of portlet services. The <code>SportletServiceFactory</code> is also
 * responsible for portlet service lifecycle management including
 * initialization and shutdown.
 */
public class SportletServiceFactory implements PortletServiceFactory, PortletSessionListener {

    private static PortletLog log = SportletLog.getInstance(SportletServiceFactory.class);
    private static SportletServiceFactory instance = null;
    private static AccessControlManager aclManager = AccessControlManager.getInstance();
    private static PortletSessionManager portletSessionManager = PortletSessionManager.getInstance();
    private static UserSessionManager userSessionManager = UserSessionManager.getInstance();


    // Maintain a single copy of each service instantiated
    // as a classname and PortletServiceProvider pair
    private static Hashtable initServices = new Hashtable();

    // Hash of all services key = service interface name, value = SportletServiceDefinition
    private static Hashtable allServices = new Hashtable();

    // Hash of all user services
    private static Hashtable userServices = new Hashtable();

    // Hash of all user services
    private static Hashtable serviceContexts = new Hashtable();


    /**
     * Private constructor. Use getDefault() instead.
     */
    private SportletServiceFactory() {
        // Reads in the service definitions from the xml file and stores them in allServices
        // organized according to service interface keys and service definition values
        String servicesPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/PortletMaster.xml");
        String servicesMappingPath = GridSphereConfig.getServletContext().getRealPath("/WEB-INF/mapping/portlet-services-mapping.xml");
        addServices(GridSphereConfig.getServletContext(), servicesPath, servicesMappingPath);
    }

    public void login(PortletRequest req) throws PortletException {

    }

    public void logout(PortletSession session) throws PortletException {
        log.debug("in logout of SportletServiceFactory");
        String userid = userSessionManager.getUserIdFromSession(session);
        if ((userid != null) && (userServices.containsKey(userid))) {
            log.debug("Removing services for userid: " + userid);
            Map servs = (Map)userServices.get(userid);
            Collection c = servs.values();
            Iterator it = c.iterator();
            while (it.hasNext()) {
                PortletServiceProvider psp = (PortletServiceProvider)it.next();
                psp.destroy();
                psp = null;
            }
            userServices.remove(userid);
        }
    }

    /**
     * Umarshalls services from the descriptor file found in servicesPath
     * using the mapping file specified
     *
     * @param servicesPath the path to the portlet services descriptor file
     * @param mappingPath the path to the portlet services mapping file
     */
    public synchronized void addServices(ServletContext ctx, String servicesPath, String mappingPath) {
        SportletServiceDescriptor descriptor = null;
        try {
            descriptor = new SportletServiceDescriptor(servicesPath, mappingPath);
        } catch (IOException e) {
            log.error("IO error unmarshalling " + servicesPath + " using " + mappingPath + " : " + e.getMessage());
            return;
        } catch (PersistenceManagerException e) {
            log.error("Unable to unmarshall " + servicesPath + " using " + mappingPath + " : " + e.getMessage());
            return;
        }
        SportletServiceCollection serviceCollection = descriptor.getServiceCollection();
        List services = serviceCollection.getPortletServicesList();
        Iterator it = services.iterator();
        while (it.hasNext()) {
            SportletServiceDefinition serviceDef = (SportletServiceDefinition) it.next();
            allServices.put(serviceDef.getServiceInterface(), serviceDef);
            log.debug("adding service: " + serviceDef.getServiceInterface() + " service def: " + serviceDef.toString());
            serviceContexts.put(serviceDef.getServiceInterface(), ctx);
        }
    }

    public static synchronized SportletServiceFactory getInstance() {
        if (instance == null) {
            instance = new SportletServiceFactory();
        }
        return instance;
    }

    /**
     * createPortletServiceFactory instantiates the given class and initializes it. The portlet service properties
     * file must be specified in the ServletContext as an InitParameter with the "PortletServices.properties" key.
     * If no properties file is found or any error occurs an exception is thrown.
     *
     * @param service the class of the service
     * @param servletContext the servlet configuration
     * @return the instantiated portlet service
     * @throws PortletServiceUnavailableException if the portlet service is unavailable
     * @throws PortletServiceNotFoundException if the PortletService is not found
     */
    public PortletService createPortletService(Class service,
                                               ServletContext servletContext,
                                               boolean useCachedService)
            throws PortletServiceUnavailableException, PortletServiceNotFoundException {

        PortletServiceProvider psp = null;

        // see if we already have an instance of this service
        if (service == null) {
            throw new PortletServiceUnavailableException("Received null service class");
        }

        String serviceName = service.getName();
        // if init'ed service exists then use it
        if (useCachedService) {
            psp = (PortletServiceProvider) initServices.get(serviceName);
            if (psp != null) return psp;
        }

        SportletServiceDefinition def = (SportletServiceDefinition) allServices.get(serviceName);
        if (def == null) {
            log.error("Unable to find portlet service interface: " + serviceName +
                    " . Please check PortletServices.xml file for proper service entry");
            throw new PortletServiceNotFoundException("Unable to find portlet service: " + serviceName);
        }

        // if user is required then pass in Guest user privileges
        if (def.getUserRequired()) {
            return createUserPortletService(service, GuestUser.getInstance(), servletContext, useCachedService);
        }

        /* Create the service implementation */
        String serviceImpl = def.getServiceImplementation();
        if (serviceImpl == null) {
            log.error("Unable to find implementing portlet service: " + serviceName +
                    " . Please check PortletServices.xml file for proper service entry");
            throw new PortletServiceNotFoundException("Unable to find implementing portlet service for interface: " + serviceName);
        }

        Properties configProperties = def.getConfigProperties();

        ServletContext ctx = (ServletContext)serviceContexts.get(serviceName);
        PortletServiceConfig portletServiceConfig = new SportletServiceConfig(service, configProperties, ctx);

        try {
            psp = (PortletServiceProvider) Class.forName(serviceImpl).newInstance();
        }
        catch (InstantiationException e) {
            // InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason. 
            log.error("Unable to create portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to create portlet service: " + serviceImpl + " Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails for some other reason.", e);
        }
        catch (IllegalAccessException e) {
            // IllegalAccessException - if the class or its nullary constructor is not accessible. 
            log.error("Unable to create portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to create portlet service: " + serviceImpl + " class or its nullary constructor is not accessible." , e);
        }
        catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            log.error("Unable to create portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to create portlet service: " + serviceImpl + " Class not found.", e);
        }
        catch (ExceptionInInitializerError e) {
            // the initialization provoked by this method fails.
            log.error("Unable to create portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to create portlet service: " + serviceImpl + " the initialization provoked by this method fails.", e);
        }
        catch (Exception e) {
            log.error("Unable to create portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to create portlet service: " + serviceImpl, e);
        }
        
        try {
            psp.init(portletServiceConfig);
        } catch (PortletServiceUnavailableException e) {
            log.error("Unable to initialize portlet service: " + serviceImpl, e);
            throw new PortletServiceNotFoundException("Unable to initialize portlet service: " + serviceImpl, e);
        }

        initServices.put(serviceName, psp);
        return psp;
    }
{'fraction_non_alphanumeric': 0.08013920671243326, 'fraction_numerical': 0.0, 'mean_word_length': 3.1853551476456503, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4673223', 'n_tokens_mistral': 5124, 'n_tokens_neox': 4979, 'n_words': 1462}