<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.sling.launchpad.base.webapp;

import static org.apache.felix.framework.util.FelixConstants.LOG_LEVEL_PROP;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.felix.framework.Logger;
import org.apache.felix.http.proxy.ProxyServlet;
import org.apache.sling.launchpad.base.impl.ClassLoaderResourceProvider;
import org.apache.sling.launchpad.base.impl.ResourceProvider;
import org.apache.sling.launchpad.base.impl.Sling;
import org.apache.sling.launchpad.base.shared.Launcher;
import org.apache.sling.launchpad.base.shared.Notifiable;
import org.apache.sling.launchpad.base.shared.SharedConstants;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;

/**
 * The <code>SlingServletDelegate</code> serves as a basic servlet for Project Sling.
 * The tasks of this servlet are as follows:
 * <ul>
 * <li>The {@link #init()} method launches Apache <code>Felix</code> as the
 * OSGi framework implementation we use.
 * <li>Registers as a service listener interested for services of type
 * <code>javax.servlet.Servlet</code>.
 * <li>Handles requests by delegating to a servlet which is expected to be
 * registered with the framework as a service of type
 * <code>javax.servlet.Servlet</code>. If no delegatee servlet has been
 * registered request handlings results in a temporary unavailability of the
 * servlet.
 * </ul>
 * <p>
 * <b>Request Handling</b>
 * <p>
 * This servlet handles request by forwarding to a delegatee servlet. The
 * delegatee servlet is automatically retrieved from the service registry by the
 * {@link #getDelegatee()}. This method also makes sure, the such a servlet
 * actually exits by throwing an <code>UnvailableException</code> if not and
 * also makes sure the servlet is initialized.
 * <p>
 * <b>Launch Configuration</b>
 * <p>
 * The Apache <code>Felix</code> framework requires configuration parameters
 * to be specified for startup. This servlet builds the list of parameters from
 * three locations:
 * <ol>
 * <li>The <code>sling.properties</code> is read
 * from the servlet class path. This properties file contains default settings.</li>
 * <li>Extensions of this servlet may provide additional properties to be
 * loaded overwriting the {@link #loadConfigProperties(String)} method.
 * <li>Finally, web application init parameters are added to the properties and
 * may overwrite existing properties of the same name(s).
 * </ol>
 * <p>
 * After loading all properties, variable substitution takes place on the
 * property values. A variable is indicated as <code>${&lt;prop-name&gt;}</code>
 * where <code>&lt;prop-name&gt;</code> is the name of a system or
 * configuration property (configuration properties override system properties).
 * Variables may be nested and are resolved from inner-most to outer-most. For
 * example, the property value <code>${outer-${inner}}</code> is resolved by
 * first resolving <code>${inner}</code> and then resolving the property whose
 * name is the catenation of <code>outer-</code> and the result of resolving
 * <code>${inner}</code>.
 * <p>
 * <b>Logging</b>
 * <p>
 * This servlet logs through the servlet container logging mechanism by calling
 * the <code>GenericServlet.log</code> methods. Bundles launched within the
 * framework provided by this servlet may use whatever logging mechanism they
 * choose to use. The Commons OSGI Log Bundle provides an OSGi Log Service
 * implementation, which also provides access to Apache Commons Logging, SLF4J
 * and Log4J logging. It is recommended that this bundle is used to setup and
 * configure logging for systems based on this servlet.
 */
public class SlingServletDelegate extends GenericServlet implements Launcher {

    /** Pseduo class version ID to keep the IDE quite. */
    private static final long serialVersionUID = 1L;

    /** Mapping between log level numbers and names */
    private static final String[] logLevels = { "FATAL", "ERROR", "WARN",
        "INFO", "DEBUG" };

    /**
     * The Sling configuration property name setting the initial log level
     * (corresponds to LogbackManager.LOG_LEVEL constant)
     */
    private static final String PROP_LOG_LEVEL = "org.apache.sling.commons.log.level";

    /**
     * The name of the configuration property defining the obr repository.
     */
    private static final String OBR_REPOSITORY_URL = "obr.repository.url";

    /**
     * Flag set by the {@link #destroy()} method to indicate the servlet has
     * been destroyed. This flag is used by the {@link #startSling(String)}
     * method to check whether the SlingServletDelegate has been destroyed while Sling
     * was starting up.
     */
    private boolean servletDestroyed = false;

    /**
     * The <code>Felix</code> instance loaded on {@link #init()} and stopped
     * on {@link #destroy()}.
     */
    private SlingBridge sling;

    /**
     * The map of delegatee servlets to which requests are delegated. This map
     * is managed through the
     * {@link #serviceChanged(ServiceEvent) service listener} based on servlets
     * registered.
     *
     * @see #getDelegatee()
     * @see #ungetDelegatee(Object)
     */
    private Servlet delegatee;

    private Notifiable notifiable;

    private String slingHome;

    public void setNotifiable(Notifiable notifiable) {
        this.notifiable = notifiable;
    }

    public void setCommandLine(Map<String, String> args) {
        // ignore this for now
    }

    public void setSlingHome(String slingHome) {
        this.slingHome = slingHome;
    }

    public boolean start() {
        // might want to log, why we don't start !
        return false;
    }

    public void stop() {
        destroy();
    }

   /**
     * Initializes this servlet by loading the framework configuration
     * properties, starting the OSGi framework (Apache Felix) and exposing the
     * system bundle context and the <code>Felix</code> instance as servlet
     * context attributes.
     *
     * @throws ServletException if the framework cannot be initialized.
     */
    public final void init() throws ServletException {
        // temporary holders control final setup and ensure proper
        // disposal in case of setup errors
        SlingBridge tmpSling = null;
        Servlet tmpDelegatee = null;

        try {

            log("Starting Sling in " + slingHome);

            // read the default parameters
            Map<String, String> props = loadConfigProperties(slingHome);

            Logger logger = new ServletContextLogger(getServletContext());
            logger.log(Logger.LOG_ERROR, "msg without exception");
            ResourceProvider rp = new ServletContextResourceProvider(
                getServletContext());
            tmpSling = new SlingBridge(notifiable, logger, rp, props, getServletContext());

            // set up the OSGi HttpService proxy servlet
            tmpDelegatee = new ProxyServlet();
            tmpDelegatee.init(getServletConfig());

            // set the fields only if the SlingServletDelegate has no been destroyed
            // while Sling has been starting up. Otherwise we do not set the
            // fields and leave the temporary variables assigned to have
            // them destroyed in the finally clause.
            if (servletDestroyed) {

                log("SlingServletDelegate destroyed while starting Sling, shutting Sling down");

            } else {<commit_msg>did not mean to leave this error message in the code; was used for testing SLING-1484<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.sling.launchpad.base.webapp;

import static org.apache.felix.framework.util.FelixConstants.LOG_LEVEL_PROP;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.felix.framework.Logger;
import org.apache.felix.http.proxy.ProxyServlet;
import org.apache.sling.launchpad.base.impl.ClassLoaderResourceProvider;
import org.apache.sling.launchpad.base.impl.ResourceProvider;
import org.apache.sling.launchpad.base.impl.Sling;
import org.apache.sling.launchpad.base.shared.Launcher;
import org.apache.sling.launchpad.base.shared.Notifiable;
import org.apache.sling.launchpad.base.shared.SharedConstants;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;

/**
 * The <code>SlingServletDelegate</code> serves as a basic servlet for Project Sling.
 * The tasks of this servlet are as follows:
 * <ul>
 * <li>The {@link #init()} method launches Apache <code>Felix</code> as the
 * OSGi framework implementation we use.
 * <li>Registers as a service listener interested for services of type
 * <code>javax.servlet.Servlet</code>.
 * <li>Handles requests by delegating to a servlet which is expected to be
 * registered with the framework as a service of type
 * <code>javax.servlet.Servlet</code>. If no delegatee servlet has been
 * registered request handlings results in a temporary unavailability of the
 * servlet.
 * </ul>
 * <p>
 * <b>Request Handling</b>
 * <p>
 * This servlet handles request by forwarding to a delegatee servlet. The
 * delegatee servlet is automatically retrieved from the service registry by the
 * {@link #getDelegatee()}. This method also makes sure, the such a servlet
 * actually exits by throwing an <code>UnvailableException</code> if not and
 * also makes sure the servlet is initialized.
 * <p>
 * <b>Launch Configuration</b>
 * <p>
 * The Apache <code>Felix</code> framework requires configuration parameters
 * to be specified for startup. This servlet builds the list of parameters from
 * three locations:
 * <ol>
 * <li>The <code>sling.properties</code> is read
 * from the servlet class path. This properties file contains default settings.</li>
 * <li>Extensions of this servlet may provide additional properties to be
 * loaded overwriting the {@link #loadConfigProperties(String)} method.
 * <li>Finally, web application init parameters are added to the properties and
 * may overwrite existing properties of the same name(s).
 * </ol>
 * <p>
 * After loading all properties, variable substitution takes place on the
 * property values. A variable is indicated as <code>${&lt;prop-name&gt;}</code>
 * where <code>&lt;prop-name&gt;</code> is the name of a system or
 * configuration property (configuration properties override system properties).
 * Variables may be nested and are resolved from inner-most to outer-most. For
 * example, the property value <code>${outer-${inner}}</code> is resolved by
 * first resolving <code>${inner}</code> and then resolving the property whose
 * name is the catenation of <code>outer-</code> and the result of resolving
 * <code>${inner}</code>.
 * <p>
 * <b>Logging</b>
 * <p>
 * This servlet logs through the servlet container logging mechanism by calling
 * the <code>GenericServlet.log</code> methods. Bundles launched within the
 * framework provided by this servlet may use whatever logging mechanism they
 * choose to use. The Commons OSGI Log Bundle provides an OSGi Log Service
 * implementation, which also provides access to Apache Commons Logging, SLF4J
 * and Log4J logging. It is recommended that this bundle is used to setup and
 * configure logging for systems based on this servlet.
 */
public class SlingServletDelegate extends GenericServlet implements Launcher {

    /** Pseduo class version ID to keep the IDE quite. */
    private static final long serialVersionUID = 1L;

    /** Mapping between log level numbers and names */
    private static final String[] logLevels = { "FATAL", "ERROR", "WARN",
        "INFO", "DEBUG" };

    /**
     * The Sling configuration property name setting the initial log level
     * (corresponds to LogbackManager.LOG_LEVEL constant)
     */
    private static final String PROP_LOG_LEVEL = "org.apache.sling.commons.log.level";

    /**
     * The name of the configuration property defining the obr repository.
     */
    private static final String OBR_REPOSITORY_URL = "obr.repository.url";

    /**
     * Flag set by the {@link #destroy()} method to indicate the servlet has
     * been destroyed. This flag is used by the {@link #startSling(String)}
     * method to check whether the SlingServletDelegate has been destroyed while Sling
     * was starting up.
     */
    private boolean servletDestroyed = false;

    /**
     * The <code>Felix</code> instance loaded on {@link #init()} and stopped
     * on {@link #destroy()}.
     */
    private SlingBridge sling;

    /**
     * The map of delegatee servlets to which requests are delegated. This map
     * is managed through the
     * {@link #serviceChanged(ServiceEvent) service listener} based on servlets
     * registered.
     *
     * @see #getDelegatee()
     * @see #ungetDelegatee(Object)
     */
    private Servlet delegatee;

    private Notifiable notifiable;

    private String slingHome;

    public void setNotifiable(Notifiable notifiable) {
        this.notifiable = notifiable;
    }

    public void setCommandLine(Map<String, String> args) {
        // ignore this for now
    }

    public void setSlingHome(String slingHome) {
        this.slingHome = slingHome;
    }

    public boolean start() {
        // might want to log, why we don't start !
        return false;
    }

    public void stop() {
        destroy();
    }

   /**
     * Initializes this servlet by loading the framework configuration
     * properties, starting the OSGi framework (Apache Felix) and exposing the
     * system bundle context and the <code>Felix</code> instance as servlet
     * context attributes.
     *
     * @throws ServletException if the framework cannot be initialized.
     */
    public final void init() throws ServletException {
        // temporary holders control final setup and ensure proper
        // disposal in case of setup errors
        SlingBridge tmpSling = null;
        Servlet tmpDelegatee = null;

        try {

            log("Starting Sling in " + slingHome);

            // read the default parameters
            Map<String, String> props = loadConfigProperties(slingHome);

            Logger logger = new ServletContextLogger(getServletContext());
            ResourceProvider rp = new ServletContextResourceProvider(
                getServletContext());
            tmpSling = new SlingBridge(notifiable, logger, rp, props, getServletContext());

            // set up the OSGi HttpService proxy servlet
            tmpDelegatee = new ProxyServlet();
            tmpDelegatee.init(getServletConfig());

            // set the fields only if the SlingServletDelegate has no been destroyed
            // while Sling has been starting up. Otherwise we do not set the
            // fields and leave the temporary variables assigned to have
            // them destroyed in the finally clause.
            if (servletDestroyed) {

                log("SlingServletDelegate destroyed while starting Sling, shutting Sling down");

            } else {
{'fraction_non_alphanumeric': 0.08461670578805748, 'fraction_numerical': 0.001030514684834259, 'mean_word_length': 3.4618135376756065, 'pattern_counts': {'":': 0, '<': 119, '<?xml version=': 0, '>': 119, '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': '4945204', 'n_tokens_mistral': 4622, 'n_tokens_neox': 4477, 'n_words': 1811}