<repo_name>nalakas/carbon-commons-1<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/registry/RegistryManager.java
/*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * Licensed 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.wso2.carbon.logging.service.registry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.net.SyslogAppender;
import org.wso2.carbon.core.RegistryResources;
import org.wso2.carbon.core.util.CryptoException;
import org.wso2.carbon.core.util.CryptoUtil;
import org.wso2.carbon.utils.logging.CircularBuffer;
import org.wso2.carbon.logging.service.appender.CarbonMemoryAppender;
import org.wso2.carbon.logging.service.config.SyslogConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfiguration;
import org.wso2.carbon.logging.service.data.SyslogData;
import org.wso2.carbon.logging.service.util.LoggingConstants;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.utils.ServerConstants;

import java.io.File;
import java.io.IOException;

public class RegistryManager {
    private static Log log = LogFactory.getLog(RegistryManager.class);

    private static Registry registry;

    public static void setRegistry(Registry registryParam) {
        registry = registryParam;
    }

    public String getConfigurationProperty(String propertyName)
            throws RegistryException {
        String resourcePath = RegistryResources.LOGGING + propertyName;
        String value = null;
        if (registry.resourceExists(resourcePath)) {
            Resource resource = registry.get(resourcePath);
            value = resource.getProperty(propertyName);
        }
        return value;
    }

    public void updateConfigurationProperty(String propertyName, String value)
            throws RegistryException {
        if (propertyName == null || value == null) {
            return;
        }
        String resourcePath = RegistryResources.LOGGING + propertyName;
        Resource resource;
        if (!registry.resourceExists(resourcePath)) {
            resource = registry.newResource();
            resource.addProperty(propertyName, value);
            registry.put(resourcePath, resource);
        } else {
            resource = registry.get(resourcePath);
            String existingValue = resource.getProperty(propertyName);
            if (!(existingValue != null && existingValue.equals(value))) {
                resource.setProperty(propertyName, value);
                registry.put(resourcePath, resource);
            }
        }
    }

    /**
     * when getting loggers from getCurrentLoggers method it will return all the
     * loggers in the system. this includes loggers we have initialized using
     * getLogger methods. but these loggers does not have a log level set they
     * get the log level from the parent loggers. but to store in registry we
     * use only loggers with a log level
     * <p/>
     * Store the provided Log4J Logger in the Registry
     *
     * @param logger The Log4J Logger to be stored in the registry
     */
    public void addLogger(Logger logger) throws Exception {
        try {
            registry.beginTransaction();
            Resource loggerResource = registry.newResource();
            loggerResource.addProperty(LoggingConstants.LoggerProperties.NAME,
                    logger.getName());
            loggerResource.addProperty(
                    LoggingConstants.LoggerProperties.LOG_LEVEL, logger
                            .getEffectiveLevel().toString());
            loggerResource.addProperty(
                    LoggingConstants.LoggerProperties.ADDITIVITY,
                    Boolean.toString(logger.getAdditivity()));

            registry.put(LoggingConstants.LOGGERS + logger.getName(),
                    loggerResource);
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Unable to add the logger", e);
            throw e;
        }
    }

    public Resource getLogger(String loggerName) throws Exception {
        String loggerResourcePath = LoggingConstants.LOGGERS + loggerName;
        if (registry.resourceExists(loggerResourcePath)) {
            return registry.get(loggerResourcePath);
        }
        return null;
    }

    public Collection getLoggers() throws Exception {
        if (registry.resourceExists(LoggingConstants.LOGGERS)) {
            return (Collection) registry.get(LoggingConstants.LOGGERS);
        }
        return null;
    }

    public void updateLogger(String loggerName, String loggerLevel,
                             boolean aditivity) throws Exception {
        try {
            registry.beginTransaction();
            Resource loggerResource;
            String loggerResourcePath = LoggingConstants.LOGGERS + loggerName;
            if (registry.resourceExists(loggerResourcePath)) {
                loggerResource = registry.get(loggerResourcePath);
                loggerResource.setProperty(
                        LoggingConstants.LoggerProperties.LOG_LEVEL,
                        loggerLevel);
                loggerResource.setProperty(
                        LoggingConstants.LoggerProperties.ADDITIVITY,
                        Boolean.toString(aditivity));
                registry.put(loggerResourcePath, loggerResource);
            } else {
                loggerResource = registry.newResource();
                loggerResource.addProperty(
                        LoggingConstants.LoggerProperties.NAME, loggerName);
                loggerResource.addProperty(
                        LoggingConstants.LoggerProperties.LOG_LEVEL,
                        loggerLevel);
                loggerResource.addProperty(
                        LoggingConstants.LoggerProperties.ADDITIVITY,
                        Boolean.toString(aditivity));
                registry.put(loggerResourcePath, loggerResource);
            }
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Unable to update the logger", e);
            throw e;
        }
    }

    private String encriptSyslogPassword(String password)
            throws CryptoException {
        return CryptoUtil.getDefaultCryptoUtil().encryptAndBase64Encode(
                password.getBytes());
    }

    private String decriptPassword(String encriptedPassword)
            throws CryptoException, IOException {
        return new String(CryptoUtil.getDefaultCryptoUtil()
                .base64DecodeAndDecrypt(encriptedPassword));
    }


    public void addSyslogConfig(SyslogData syslogData) throws Exception {
        try {
            registry.beginTransaction();
            Resource syslogResource = registry.newResource();
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.LOG_INDEX_URL,
                    syslogData.getUrl());
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.SYSLOG_PORT,
                    syslogData.getPort());
            syslogResource.addProperty(LoggingConstants.SyslogProperties.REALM,
                    syslogData.getRealm());
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.USER_NAME,
                    syslogData.getUserName());
            syslogResource.addProperty(
                    LoggingConstants.SyslogProperties.PASSWORD,
                    encriptSyslogPassword(syslogData.getPassword()));
            registry.put(LoggingConstants.SYSLOG, syslogResource);
            registry.commitTransaction();
        } catch (RegistryException e) {
            registry.rollbackTransaction();
            log.error("Cannot add syslog properties ", e);
            throw e;
        }
    }

    /**
     * Store the provided Log4J Appender in the Registry
     *
     * @param appender Log4J Appender to be stored in the registry
     */
    public void addAppender(Appender appender) throws Exception {
        try {
            registry.beginTransaction();
            Resource appenderResource = registry.newResource();
            if (appender.requiresLayout()) {
                Layout layout = appender.getLayout();
                if (layout instanceof PatternLayout) {
                    appenderResource.addProperty(
                            LoggingConstants.AppenderProperties.PATTERN,
                            ((PatternLayout) layout).getConversionPattern());
                }
            }

            if (appender instanceof FileAppender) {
                FileAppender fileAppender = (FileAppender) appender;
                String fileName = fileAppender.getFile();
                File logFile = new File(fileName);
                if (!logFile.isAbsolute()) {
                    if (fileName.startsWith(".")) {
                        fileName = fileName.substring(1);
                    }
                    fileName = (System.getProperty(ServerConstants.CARBON_HOME)
                            + "/" + fileName).replace('\\', '/');
                    fileAppender.setFile(fileName);
                    fileAppender.activateOptions();
                }
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.LOG_FILE_NAME,
                        fileName);
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.IS_FILE_APPENDER,
                        Boolean.toString(true));
            } else {
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.IS_FILE_APPENDER,
                        Boolean.toString(false));
            }

            if (appender instanceof CarbonMemoryAppender) {
                CarbonMemoryAppender memoryAppender = (CarbonMemoryAppender) appender;
                memoryAppender.setCircularBuffer(new CircularBuffer(
                        LoggingConstants.MEMORY_APPENDER_BUFFER_SZ));
                memoryAppender.activateOptions();
            }

            // normally all the appenders inherit from AppenderSkelton
            if (appender instanceof AppenderSkeleton) {
                AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                if (appenderSkeleton.getThreshold() != null) {
                    appenderResource.addProperty(
                            LoggingConstants.AppenderProperties.THRESHOLD,
                            appenderSkeleton.getThreshold().toString());
                } else {
                    appenderResource.addProperty(
                            LoggingConstants.AppenderProperties.THRESHOLD,
                            "DEBUG");
                }
            }

            if (appender instanceof SyslogAppender) {
                SyslogAppender syslogAppender = (SyslogAppender) appender;

                // if user has not set these properties system automatically
                // assign default values
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.SYS_LOG_HOST,
                        syslogAppender.getSyslogHost());
                appenderResource.addProperty(
                        LoggingConstants.AppenderProperties.FACILITY,
                        syslogAppender.getFacility());
                appenderResource
                        .addProperty(
                                LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER,
                                Boolean.toString(true));
            } else {
                appenderResource
                        .addProperty(
                                LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER,
                                Boolean.toString(false));
            }
            registry.put(LoggingConstants.APPENDERS + appender.getName(),
                    appenderResource);
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Cannot add appender", e);
            throw e;
        }
    }

    public void updateCassandraConfig(String url, String keyspace,
                                      String columnFamily, String userName, String password)
            throws Exception {
        String cassandraResourcePath = LoggingConstants.CASSANDRA;
        try {
            if (registry.resourceExists(cassandraResourcePath)) {
                try {
                    registry.beginTransaction();
                    Resource appenderResource = registry
                            .get(cassandraResourcePath);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.URL, url);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.KEYSPACE,
                            keyspace);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.COLUMN_FAMILY,
                            columnFamily);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.USER_NAME,
                            userName);
                    appenderResource.setProperty(
                            LoggingConstants.CassandraProperties.PASSWORD,
                            encriptSyslogPassword(password));
                    registry.put(LoggingConstants.CASSANDRA, appenderResource);
                    registry.commitTransaction();
                } catch (RegistryException e) {
                    registry.rollbackTransaction();
                    log.error("Unable to update the appender", e);
                    throw e;
                }
            }
        } catch (RegistryException e) {
            log.error("Unable to update the appender", e);
            throw e;
        }
    }

    /**
     * this method is used to update syslog properties in the registry if syslog
     * property is not available a new resource is added to the registry along
     * with the syslog properties
     *
     * @param url      - syslog logs location
     * @param port     - port
     * @param realm    - realm
     * @param userName - syslog server authentic user name
     * @param password - syslog server authentic password
     * @throws Exception
     */
    public void updateSyslogConfig(String url, String port, String realm,
                                   String userName, String password) throws Exception {
        String syslogResourcePath = LoggingConstants.SYSLOG;
        try {
            if (registry.resourceExists(syslogResourcePath)) {
                try {
                    registry.beginTransaction();
                    Resource appenderResource = registry
                            .get(syslogResourcePath);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.LOG_INDEX_URL,
                            url);
                    appenderResource
                            .setProperty(
                                    LoggingConstants.SyslogProperties.SYSLOG_PORT,
                                    port);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.REALM, realm);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.USER_NAME,
                            userName);
                    appenderResource.setProperty(
                            LoggingConstants.SyslogProperties.PASSWORD,
                            encriptSyslogPassword(password));
                    registry.put(LoggingConstants.SYSLOG, appenderResource);
                    registry.commitTransaction();
                } catch (RegistryException e) {
                    registry.rollbackTransaction();
                    log.error("Unable to update the appender", e);
                    throw e;
                }
            } else {
                SyslogData syslogData = new SyslogData(url, port, realm,
                        userName, password);
                addSyslogConfig(syslogData);
            }
        } catch (RegistryException e) {
            log.error("Unable to update the appender", e);
            throw e;
        }

    }

    public SyslogData getSyslogData() throws Exception {
        Resource syslogConfigResource;
        try {
            syslogConfigResource = getSyslogConfig();
            String url = "";
            String port = "";
            String realm = "";
            String userName = "";
            String password = "";
            if (syslogConfigResource != null) { // Check if the properties are
                // coming from the registry.
                url = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.LOG_INDEX_URL);
                port = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.SYSLOG_PORT);
                realm = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.REALM);
                userName = syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.USER_NAME);
                password = <PASSWORD>(syslogConfigResource
                        .getProperty(LoggingConstants.SyslogProperties.PASSWORD));
            } else { // read syslog properties from the syslog-config.xml
                SyslogConfiguration config = SyslogConfigManager
                        .loadSyslogConfiguration();
                url = config.getSyslogHostURL();
                port = config.getPort();
                realm = config.getRealm();
                userName = config.getUserName();
                password = <PASSWORD>();
            }

            return new SyslogData(url, port, realm, userName, password);
        } catch (Exception e) {
            log.error("Unable get SyslogData ", e);
            throw e;
        }

    }

    /**
     * @return Registry resource of syslog property file.
     * @throws Exception
     */
    public Resource getSyslogConfig() throws Exception {
        String syslogResourcePath = LoggingConstants.SYSLOG;
        if (registry.resourceExists(syslogResourcePath)) {
            return registry.get(syslogResourcePath);
        }
        return null;
    }

    public Resource getCassandraConfig() throws Exception {
        String cassandraResourcePath = LoggingConstants.CASSANDRA;
        if (registry.resourceExists(cassandraResourcePath)) {
            return registry.get(cassandraResourcePath);
        }
        return null;
    }

    public void updateAppender(Appender appender, String appenderName,
                               String appenderPattern, String threshold, String logFileName,
                               String sysLogHost, String facility, boolean isFileAppender,
                               boolean isSysLogAppender) throws Exception {

        String appenderResourcePath = LoggingConstants.APPENDERS + appenderName;
        if (registry.resourceExists(appenderResourcePath)) {
            try {
                registry.beginTransaction();

                Resource appenderResource = registry.get(appenderResourcePath);
                appenderResource.setProperty(
                        LoggingConstants.AppenderProperties.PATTERN,
                        appenderPattern);

                if (isFileAppender) {
                    appenderResource.setProperty(
                            LoggingConstants.AppenderProperties.LOG_FILE_NAME,
                            logFileName);
                    appenderResource
                            .setProperty(
                                    LoggingConstants.AppenderProperties.IS_FILE_APPENDER,
                                    Boolean.toString(true));
                }

                if (isSysLogAppender) {
                    appenderResource.setProperty(
                            LoggingConstants.AppenderProperties.SYS_LOG_HOST,
                            sysLogHost);
                    appenderResource.setProperty(
                            LoggingConstants.AppenderProperties.FACILITY,
                            facility);
                    appenderResource
                            .setProperty(
                                    LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER,
                                    Boolean.toString(true));
                }

                appenderResource.setProperty(
                        LoggingConstants.AppenderProperties.THRESHOLD,
                        threshold);
                registry.put(LoggingConstants.APPENDERS + appenderName,
                        appenderResource);

                registry.commitTransaction();
            } catch (Exception e) {
                registry.rollbackTransaction();
                log.error("Unable to update the appender", e);
                throw e;
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("appender " + appenderName
                        + " is not available, therefore adding to registry");
            }
            addAppender(appender);
            updateAppender(appender, appenderName, appenderPattern, threshold,
                    logFileName, sysLogHost, facility, isFileAppender,
                    isSysLogAppender);
        }
    }

    public Resource getAppender(String appenderName) throws Exception {
        String appenderResourcePath = LoggingConstants.APPENDERS + appenderName;
        if (registry.resourceExists(appenderResourcePath)) {
            return registry.get(appenderResourcePath);
        }
        return null;
    }

    public Collection getAppenders() throws Exception {
        if (registry.resourceExists(LoggingConstants.APPENDERS)) {
            return (Collection) registry.get(LoggingConstants.APPENDERS);
        }
        return null;
    }

    /**
     * method is used to check current appender is a syslog appender.
     *
     * @return isSyslogAppender
     * @throws RegistryException
     */
    public boolean isSysLogAppender() throws RegistryException {
        boolean isSyslogAppender = false;
        String appenderResourcePath = LoggingConstants.APPENDERS
                + LoggingConstants.WSO2CARBON_SYS_LOG_APPENDER;
        if (registry.resourceExists(appenderResourcePath)) {
            Resource appenderResource = registry.get(appenderResourcePath);
            isSyslogAppender = Boolean
                    .parseBoolean(appenderResource
                            .getProperty(LoggingConstants.AppenderProperties.IS_SYS_LOG_APPENDER));
        }
        return isSyslogAppender;
    }

    public void removeAllRegistryEntries() throws Exception {
        try {
            registry.beginTransaction();
            if (registry.resourceExists(LoggingConstants.LOGGERS)) {
                registry.delete(LoggingConstants.LOGGERS);
            }
            if (registry.resourceExists(LoggingConstants.APPENDERS)) {
                registry.delete(LoggingConstants.APPENDERS);
            }

            if (registry.resourceExists(RegistryResources.LOGGING
                    + LoggingConstants.SYSTEM_LOG_PATTERN)) {
                registry.delete(RegistryResources.LOGGING
                        + LoggingConstants.SYSTEM_LOG_PATTERN);
            }
            if (registry.resourceExists(RegistryResources.LOGGING
                    + LoggingConstants.SYSTEM_LOG_LEVEL)) {
                registry.delete(RegistryResources.LOGGING
                        + LoggingConstants.SYSTEM_LOG_LEVEL);
            }
            registry.commitTransaction();
        } catch (Exception e) {
            registry.rollbackTransaction();
            log.error("Unable to remove all the loggers and appenders", e);
            throw e;
        }
    }
}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggingConfig.java
/*
 * Copyright The Apache Software Foundation.
 *
 * Licensed 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.wso2.carbon.logging.service.data;

import java.util.HashMap;
import java.util.Map;

public class LoggingConfig {

    private String logProviderImplClassName;
    private String logFileProviderImplClassName;

    private Map<String, String> logProviderPropMap = new HashMap<String, String>();
    private Map<String, String> logFileProviderPropMap = new HashMap<String, String>();

    public LoggingConfig() {
    }


    public void setLogProviderProperty(String key, String value) {
        this.logProviderPropMap.put(key, value);
    }

    public void setLogFileProviderProperty(String key, String value) {
        this.logFileProviderPropMap.put(key, value);
    }

    public String getLogProviderProperty(String key) {
        return this.logProviderPropMap.get(key);
    }

    public String getLogFileProviderProperty(String key) {
        return this.logFileProviderPropMap.get(key);
    }

    public String getLogProviderImplClassName() {
        return logProviderImplClassName;
    }

    public void setLogProviderImplClassName(String logProviderImplClassName) {
        if (logProviderImplClassName == null | logProviderImplClassName.equals("")) {
            throw new IllegalArgumentException("LogProvider implementation class name should not be null or empty");
        }
        this.logProviderImplClassName = logProviderImplClassName;
    }

    public String getLogFileProviderImplClassName() {
        return logFileProviderImplClassName;
    }

    public void setLogFileProviderImplClassName(String logFileProviderImplClassName) {
        if (logFileProviderImplClassName == null | logFileProviderImplClassName.equals("")) {
            throw new IllegalArgumentException("LogProvider implementation class name should not be null or empty");
        }
        this.logFileProviderImplClassName = logFileProviderImplClassName;
    }
}
<file_sep>/components/deployment-synchronizer/org.wso2.carbon.deployment.synchronizer.git/src/main/java/org/wso2/carbon/deployment/synchronizer/git/GitDeploymentSynchronizerComponent.java
package org.wso2.carbon.deployment.synchronizer.git;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.deployment.synchronizer.ArtifactRepository;


/**
 * @scr.component name="org.wso2.carbon.deployment.synchronizer.git" immediate="true"
 */
public class GitDeploymentSynchronizerComponent {

    private static final Log log = LogFactory.getLog(GitDeploymentSynchronizerComponent.class);

    private ServiceRegistration gitDepSyncServiceRegistration;

    /**
     * Activate Git Deployment Synchronizer Component
     *
     * @param context ComponentContext instance to access osgi runtime
     */
    protected void activate(ComponentContext context) {

        ArtifactRepository gitBasedArtifactRepository = new GitBasedArtifactRepository();
        gitDepSyncServiceRegistration = context.getBundleContext().registerService(ArtifactRepository.class.getName(),
                gitBasedArtifactRepository, null);

        /*ServerConfiguration serverConf = ServerConfiguration.getInstance();
        String depSyncEnabledParam = serverConf.getFirstProperty(GitDeploymentSynchronizerConstants.ENABLED);

        //Check if deployment synchronization is enabled
        if (depSyncEnabledParam != null && depSyncEnabledParam.equals("true")) {

            //check if repository type is 'git', else no need to create GitBasedArtifactRepository instance
            String repoTypeParam = serverConf.getFirstProperty(GitDeploymentSynchronizerConstants.REPOSITORY_TYPE);
            if (repoTypeParam != null && repoTypeParam.equals(DeploymentSynchronizerConstants.REPOSITORY_TYPE_GIT)) {

                ArtifactRepository gitBasedArtifactRepository = new GitBasedArtifactRepository();
                gitDepSyncServiceRegistration = context.getBundleContext().registerService(ArtifactRepository.class.getName(),
                        gitBasedArtifactRepository, null);
            }
            else {
                if(log.isDebugEnabled()) {
                    log.debug("Git deployment synchronization disabled, GitBasedArtifactRepository instance not created");
                }
            }
        }
        else {
            if(log.isDebugEnabled()) {
                log.debug("Deployment synchronization disabled, GitBasedArtifactRepository instance not created");
            }
        }*/

        if(log.isDebugEnabled()) {
            log.debug("Git based deployment synchronizer component activated");
        }
    }

    /**
     * De-activate Git Deployment Synchronizer Component
     *
     * @param context ComponentContext instance to access osgi runtime
     */
    protected void deactivate(ComponentContext context) {

        if(gitDepSyncServiceRegistration != null){
            gitDepSyncServiceRegistration.unregister();
            gitDepSyncServiceRegistration = null;
        }

        if(log.isDebugEnabled()) {
            log.debug("Git based deployment synchronizer component deactivated");
        }
    }

}
<file_sep>/components/deployment-synchronizer/org.wso2.carbon.deployment.synchronizer.subversion/src/main/java/org/wso2/carbon/deployment/synchronizer/subversion/SVNDeploymentSynchronizerComponent.java
/*
*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. 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.wso2.carbon.deployment.synchronizer.subversion;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.tigris.subversion.svnclientadapter.commandline.CmdLineClientAdapterFactory;
import org.tigris.subversion.svnclientadapter.javahl.JhlClientAdapterFactory;
import org.tigris.subversion.svnclientadapter.svnkit.SvnKitClientAdapterFactory;
import org.wso2.carbon.deployment.synchronizer.ArtifactRepository;
import org.wso2.carbon.deployment.synchronizer.subversion.util.SVNDataHolder;
import org.wso2.carbon.tomcat.api.CarbonTomcatService;

/**
 * @scr.component name="org.wso2.carbon.deployment.synchronizer.subversion" immediate="true"
 * @scr.reference name="carbon.tomcat.service"
 * interface="org.wso2.carbon.tomcat.api.CarbonTomcatService"
 * cardinality="0..1" policy="dynamic" bind="setCarbonTomcatService"
 * unbind="unsetCarbonTomcatService"
 */
public class SVNDeploymentSynchronizerComponent {

    private static final Log log = LogFactory.getLog(SVNDeploymentSynchronizerComponent.class);

    private ServiceRegistration svnDepSyncServiceRegistration;

    protected void activate(ComponentContext context) {
        
        boolean allClientsFailed = true;
        
        try {
            SvnKitClientAdapterFactory.setup();
            allClientsFailed = false;
            log.debug("SVN Kit client adapter initialized");
        } catch (Throwable t) {
            log.debug("Unable to initialize the SVN Kit client adapter - Required jars " +
                    "may be missing");
        }

        try {
            JhlClientAdapterFactory.setup();
            allClientsFailed = false;
            log.debug("Java HL client adapter initialized");
        } catch (Throwable t) {
            log.debug("Unable to initialize the Java HL client adapter - Required jars " +
                    " or the native libraries may be missing");
        }

        try {
            CmdLineClientAdapterFactory.setup();
            allClientsFailed = false;
            log.debug("Command line client adapter initialized");
        } catch (Throwable t) {
            log.debug("Unable to initialize the command line client adapter - SVN command " +
                    "line tools may be missing");
        }
        
        if(allClientsFailed){
            String error = "Could not initialize any of the SVN client adapters - " +
                    "Required jars/libraries may be missing";
            log.debug(error);
            return;
        }

        ArtifactRepository svnBasedArtifactRepository = new SVNBasedArtifactRepository();
        svnDepSyncServiceRegistration = context.getBundleContext().registerService(ArtifactRepository.class.getName(),
                svnBasedArtifactRepository, null);

        log.debug("SVN based deployment synchronizer component activated");
    }

    protected void deactivate(ComponentContext context) {

        if(svnDepSyncServiceRegistration != null){
            svnDepSyncServiceRegistration.unregister();
            svnDepSyncServiceRegistration = null;
        }

        log.debug("SVN based deployment synchronizer component deactivated");
    }

    protected void setCarbonTomcatService(CarbonTomcatService carbonTomcatService) {
        SVNDataHolder.getInstance().setCarbonTomcatService(carbonTomcatService);
    }

    protected void unsetCarbonTomcatService(CarbonTomcatService carbonTomcatService) {
        SVNDataHolder.getInstance().setCarbonTomcatService(null);
    }
}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/sync/LoggingConfigSyncRequest.java
/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. 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.wso2.carbon.logging.service.sync;


import org.apache.axis2.clustering.ClusteringCommand;
import org.apache.axis2.clustering.ClusteringFault;
import org.apache.axis2.clustering.ClusteringMessage;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.logging.service.util.LoggingUtil;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

/**
 * Cluster message to be sent when logging configurations are modified.
 */
public class LoggingConfigSyncRequest extends ClusteringMessage {

    private static final Log log = LogFactory.getLog(LoggingConfigSyncRequest.class);
    private static final long serialVersionUID = -689482772914112325L;

    public LoggingConfigSyncRequest() {
    }

    @Override
    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
        if (log.isDebugEnabled()) {
            log.debug("Received [" + this + "] ");
        }
        
        try {
            // load the configuration from registry as ST
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);
            carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

            LoggingUtil.loadCustomConfiguration();
        } catch (Exception e) {
            log.error("Cannot load logging configuration from the registry", e);
        } finally {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }

    @Override
    public ClusteringCommand getResponse() {
        return null;
    }

    @Override
    public String toString() {
        return "LoggingConfigSyncRequest{" + "messageId=" + getUuid() + "}";
    }
}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/PaginatedLogEvent.java
/*
 * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org
 * Licensed 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.wso2.carbon.logging.service.data;

import org.wso2.carbon.utils.Pageable;

import java.util.List;

public class PaginatedLogEvent implements Pageable {
    private LogEvent[] logEvt;
    private int numberOfPages;

    public int getNumberOfPages() {
        return numberOfPages;
    }

    public void setNumberOfPages(int numberOfPages) {
        this.numberOfPages = numberOfPages;
    }

    public LogEvent[] getLogInfo() {
        return logEvt;
    }

    public void setLogInfo(LogEvent[] logEvt) {
        this.logEvt = logEvt;
    }

    public <T> void set(List<T> items) {
        this.logEvt = items.toArray(new LogEvent[items.size()]);
    }

}
<file_sep>/components/deployment-synchronizer/org.wso2.carbon.deployment.synchronizer/src/main/java/org/wso2/carbon/deployment/synchronizer/internal/DeploymentSynchronizerComponent.java
/*
*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. 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.wso2.carbon.deployment.synchronizer.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.deployment.synchronizer.ArtifactRepository;
import org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizationManager;
import org.wso2.carbon.deployment.synchronizer.DeploymentSynchronizerException;
import org.wso2.carbon.deployment.synchronizer.repository.CarbonRepositoryUtils;
import org.wso2.carbon.deployment.synchronizer.services.DeploymentSynchronizerService;
import org.wso2.carbon.deployment.synchronizer.internal.util.RepositoryReferenceHolder;
import org.wso2.carbon.deployment.synchronizer.internal.util.ServiceReferenceHolder;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import org.wso2.carbon.registry.core.service.RegistryService;

/**
 * @scr.component name="org.wso2.carbon.deployment.synchronizer.XXX" immediate="true"
 * @scr.reference name="configuration.context.service"
 * interface="org.wso2.carbon.utils.ConfigurationContextService" cardinality="1..1"
 * policy="dynamic" bind="setConfigurationContextService" unbind="unsetConfigurationContextService"
 * @scr.reference name="repository.reference.service"
 * interface="org.wso2.carbon.deployment.synchronizer.ArtifactRepository" cardinality="0..n"
 * policy="dynamic" bind="addArtifactRepository" unbind="removeArtifactRepository"
 * @scr.reference name="registry.service" immediate="true"
 * interface="org.wso2.carbon.registry.core.service.RegistryService" cardinality="1..1"
 * policy="dynamic" bind="setRegistryService" unbind="unsetRegistryService"
 */

public class DeploymentSynchronizerComponent {

    private static final Log log = LogFactory.getLog(DeploymentSynchronizerComponent.class);
    private ServiceRegistration observerRegistration;

    protected void activate(ComponentContext context) {

        try {
            // Initialize the repository manager so that it can be later used to
            // start a synchronizer (eg: via the UI)
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            DeploymentSynchronizationManager.getInstance().init(serverConfig);

            try {
                initDeploymentSynchronizerForSuperTenant();
            } catch (DeploymentSynchronizerException e) {
                log.error("Error while initializing a deployment synchronizer for the super tenant " +
                          "Carbon repository", e);
            }

            // Register an observer so we can track tenant ConfigurationContext creation and
            // do the synchronization operations as necessary
            BundleContext bundleContext = context.getBundleContext();
            observerRegistration = bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
                                                                 new DeploymentSyncAxis2ConfigurationContextObserver(), null);

            // register the OSGi service
            bundleContext.registerService(new String[]{DeploymentSynchronizerService.class.getName(),
                                                       org.wso2.carbon.core.deployment.DeploymentSynchronizer.class.getName()},
                                          new DeploymentSynchronizerServiceImpl(), null);
            log.debug("Deployment synchronizer component activated");
        } catch (Throwable e) {
            log.info("Error activating Deployment Synchronizer component. " + e.getMessage(), e);
        }
    }

    private void initDeploymentSynchronizerForSuperTenant() throws DeploymentSynchronizerException {
        if (!CarbonRepositoryUtils.isSynchronizerEnabled(MultitenantConstants.SUPER_TENANT_ID)) {
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("Initializing the deployment synchronizer for super tenant");
        }

        CarbonRepositoryUtils.newCarbonRepositorySynchronizer(MultitenantConstants.SUPER_TENANT_ID);
    }

    protected void deactivate(ComponentContext context) {
        DeploymentSynchronizationManager.getInstance().shutdown();

        if (observerRegistration != null) {
            observerRegistration.unregister();
            observerRegistration = null;
        }
        log.debug("Deployment synchronizer component deactivated");
    }

    protected void setConfigurationContextService(ConfigurationContextService service) {
        if (log.isDebugEnabled()) {
            log.debug("Deployment synchronizer component bound to the " +
                    "configuration context service");
        }
        ServiceReferenceHolder.setConfigurationContextService(service);
    }

    protected void unsetConfigurationContextService(ConfigurationContextService service) {
        if (log.isDebugEnabled()) {
            log.debug("Deployment synchronizer component unbound from the " +
                    "configuration context service");
        }
        ServiceReferenceHolder.setConfigurationContextService(null);
    }

    protected void addArtifactRepository(ArtifactRepository artifactRepository){
        RepositoryReferenceHolder repositoryReferenceHolder = RepositoryReferenceHolder.getInstance();
        repositoryReferenceHolder.addRepository(artifactRepository, artifactRepository.getParameters());
    }

    protected void removeArtifactRepository(ArtifactRepository artifactRepository){
        RepositoryReferenceHolder repositoryReferenceHolder = RepositoryReferenceHolder.getInstance();
        repositoryReferenceHolder.removeRepository(artifactRepository);
    }

    protected void setRegistryService(RegistryService service) {
        if (log.isDebugEnabled()) {
            log.debug("Deployment synchronizer component bound to the registry service");
        }
        ServiceReferenceHolder.setRegistryService(service);
    }

    protected void unsetRegistryService(RegistryService service) {
        if (log.isDebugEnabled()) {
            log.debug("Deployment synchronizer component unbound from the registry service");
        }
        ServiceReferenceHolder.setRegistryService(null);
    }

}
<file_sep>/components/logging/org.wso2.carbon.logging.summarizer/src/main/java/org/wso2/carbon/logging/summarizer/scriptCreator/QueryGenerator.java
package org.wso2.carbon.logging.summarizer.scriptCreator;

/*
 * Copyright 2005,2006 WSO2, Inc. http://www.wso2.org
 *
 * Licensed 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.
 */

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.logging.summarizer.core.SummarizerException;
import org.wso2.carbon.logging.summarizer.utils.LoggingConfig;
import org.wso2.carbon.logging.summarizer.utils.LoggingConfigManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QueryGenerator {

    private static final Log log = LogFactory.getLog(QueryGenerator.class);
    LoggingConfig config = LoggingConfigManager.loadLoggingConfiguration();
    String keyspaceName = config.getKeyspace();
    String archivedLogLocation = config.getArchivedLogLocation();

    public List<String> createFilePaths() throws SummarizerException {
        ColumnFamilyHandler cfHandler = new ColumnFamilyHandler();
        List<String> selectedColFamilies = cfHandler.filterColumnFamilies(keyspaceName);
        String logFileLocation = config.getTmpLogsDirectory();
        List<String> filePathList = new ArrayList<String>(selectedColFamilies.size());


        for (int i = 0; i < selectedColFamilies.size(); i++) {
            String colFamilyName = selectedColFamilies.get(i);
            if (colFamilyName.contains("log")) {
                String[] strArrayColFamilyNameParts = colFamilyName.split("_");
                int strArrayLength = strArrayColFamilyNameParts.length;

                if (strArrayLength > 1) {
                    String tenantId = strArrayColFamilyNameParts[1];
                    if (strArrayLength > 2) {
                        String serverName = strArrayColFamilyNameParts[2];
                        for (int j = 3; j < strArrayLength - 3; j++) {
                            serverName += "_" + strArrayColFamilyNameParts[j];
                        }
                        String date = strArrayColFamilyNameParts[strArrayLength - 3] + "_" + strArrayColFamilyNameParts[strArrayLength - 2] + "_" + strArrayColFamilyNameParts[strArrayLength - 1];

                        filePathList.add(archivedLogLocation + tenantId + "/" + serverName + "/" + date);
                    }
                }
            }
        }
        return filePathList;
    }

    public Map<String, String> createQuery() throws SummarizerException {
        Map hiveQueryMap = new HashMap();
        List<String> filteredColFamilies = new ColumnFamilyHandler().filterColumnFamilies(keyspaceName);
        List<String> filePaths = createFilePaths();

        for (int i = 0; i < filePaths.size(); i++) {
            String filePath = filePaths.get(i);
            log.info(filePath);
            String columnFamilyName = "\"" + filteredColFamilies.get(i) + "\"";

            String hiveQueryTemplate = config.getHiveQuery();
            String cassandraHost = config.getCassandraHost();
            String cassandraUserName = config.getCassUsername();
            String cassandraPassword = config.getCassPassword();
            String cassandraKeySpace = config.getKeyspace();

            String hiveQuery = replaceVars(hiveQueryTemplate, filePath, columnFamilyName, cassandraHost,
                    cassandraUserName, cassandraPassword, cassandraKeySpace);
            hiveQueryMap.put(filteredColFamilies.get(i), hiveQuery);
        }

        return hiveQueryMap;
    }


    public String replaceVars(String queryTemplate, String filePath, String cfName, String cassHost, String cassUsrName,
                              String cassPswd, String cassKeySpace) {

        //When there are multiple cassandra hosts given in the summarizer-config.xml
        String[] strArrCassHostList = cassHost.split(",");
        String hosts = "";
        String cassPort = strArrCassHostList[0].substring(strArrCassHostList[0].indexOf(":") + 1,
                strArrCassHostList[0].length());
        for(String host : strArrCassHostList) {
            hosts += host.substring(0, host.indexOf(":")) + ",";
        }
        hosts = hosts.substring(0, hosts.length() - 1);

        queryTemplate = queryTemplate.replace("set logs_column_family = %s;", "set logs_column_family = " +
                cfName + ";");
        queryTemplate = queryTemplate.replace("set file_path= %s;", "set file_path = " + filePath + ";");
        queryTemplate = queryTemplate.replace("\"cassandra.host\" = %s,", "\"cassandra.host\" = \"" + hosts + "\",");
        queryTemplate = queryTemplate.replace("\"cassandra.port\" = %s,", "\"cassandra.port\" =\"" + cassPort + "\",");
        queryTemplate = queryTemplate.replace("\"cassandra.ks.name\" = %s,", "\"cassandra.ks.name\" = \"" +
                cassKeySpace + "\",");
        queryTemplate = queryTemplate.replace("\"cassandra.ks.username\" = %s,", "\"cassandra.ks.username\" = \"" +
                cassUsrName + "\",");
        queryTemplate = queryTemplate.replace("\"cassandra.ks.password\" = %s,", "\"cassandra.ks.password\" =\"" +
                cassPswd + "\",");


        return queryTemplate;
    }

}

<file_sep>/components/application-mgt/org.wso2.carbon.application.mgt/src/main/java/org/wso2/carbon/application/mgt/internal/AppManagementServiceComponent.java
/*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * Licensed 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.wso2.carbon.application.mgt.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.axis2.context.ConfigurationContext;
import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.application.deployer.service.ApplicationManagerService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.osgi.service.component.ComponentContext;

/**
 * @scr.component name="application.mgt.dscomponent" immediate="true"
 * @scr.reference name="application.manager" interface="org.wso2.carbon.application.deployer.service.ApplicationManagerService"
 * cardinality="1..1" policy="dynamic" bind="setAppManager" unbind="unsetAppManager"
 */
public class AppManagementServiceComponent {

    private static Log log = LogFactory.getLog(AppManagementServiceComponent.class);

    private static ApplicationManagerService applicationManager;

    protected void activate(ComponentContext ctxt) {
        if (log.isDebugEnabled()) {
            log.debug("Activated AppManagementServiceComponent");
        }
    }

    protected void deactivate(ComponentContext ctxt) {
        if (log.isDebugEnabled()) {
            log.debug("Deactivated AppManagementServiceComponent");
        }
    }

    protected void setAppManager(ApplicationManagerService appManager) {
        applicationManager = appManager;
    }

    protected void unsetAppManager(ApplicationManagerService appManager) {
        applicationManager = null;
    }

    public static ApplicationManagerService getAppManager() throws Exception {
        if (applicationManager == null) {
            String msg = "Before activating App management service bundle, an instance of "
                    + "ApplicationManager should be in existance";
            log.error(msg);
            throw new Exception(msg);
        }
        return applicationManager;
    }

}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LogEvent.java
/*
 * Copyright The Apache Software Foundation.
 *
 * Licensed 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.wso2.carbon.logging.service.data;

public class LogEvent {
    private String key;
    private String tenantId;
    private String serverName;
    private String appName;
    private String logTime;
    private String logger;
    private String priority;
    private String message;
    private String ip;
    private String stacktrace;
    private String instance;

    public LogEvent() {
    }


    public LogEvent(String tenantId, String serverName, String appName, String logTime,
                    String logger, String priority, String message, String ip, String stacktrace,
                    String instance) {
        super();
        this.tenantId = tenantId;
        this.serverName = serverName;
        this.appName = appName;
        this.logTime = logTime;
        this.logger = logger;
        this.priority = priority;
        this.message = message;
        this.ip = ip;
        this.stacktrace = stacktrace;
        this.instance = instance;
    }


    public LogEvent(String message, String priority) {
        this.message = message;
        this.priority = priority;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getTenantId() {
        return tenantId;
    }

    public void setTenantId(String tenantId) {
        this.tenantId = tenantId;
    }

    public String getServerName() {
        return serverName;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getLogTime() {
        return logTime;
    }

    public void setLogTime(String logTime) {
        this.logTime = logTime;
    }

    public String getLogger() {
        return logger;
    }

    public void setLogger(String logger) {
        this.logger = logger;
    }

    public String getPriority() {
        return priority;
    }

    public void setPriority(String priority) {
        this.priority = priority;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getStacktrace() {
        return stacktrace;
    }

    public void setStacktrace(String stacktrace) {
        this.stacktrace = stacktrace;
    }

    public String getInstance() {
        return instance;
    }

    public void setInstance(String instance) {
        this.instance = instance;
    }

}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/data/LoggerData.java
/*
 * Copyright 2004,2005 The Apache Software Foundation.
 *
 * Licensed 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.wso2.carbon.logging.service.data;

public class LoggerData {
    private String name;
    private String level;
    private String parentName;
    private boolean additivity;

    public LoggerData() {
    }

    public LoggerData(String name, String level, boolean aditivity, String parentName) {
        this.name = name;
        this.level = level;
        this.additivity = aditivity;
        this.parentName = parentName;
    }

    public boolean getAdditivity() {
        return additivity;
    }

    public void setAdditivity(boolean additivity) {
        this.additivity = additivity;
    }

    public String getName() {
        return name;
    }

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

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }


    public String getParentName() {
        return parentName;
    }

    public void setParentName(String parentName) {
        this.parentName = parentName;
    }
}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/sort/LogEventSorter.java
/*
 * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org
 * Licensed 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.wso2.carbon.logging.service.sort;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.logging.service.data.LogEvent;
import org.wso2.carbon.logging.service.util.LoggingConstants;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;

public class LogEventSorter implements Callable<List<LogEvent>> {

    private static LogTaskThreadPoolExecuter executer;
    private static Log log = LogFactory.getLog(LogEventSorter.class);
    private List<LogEvent> events;
    private List<LogEvent> preprocessedEvents;

    public LogEventSorter(List<LogEvent> events) {
        this.events = events;
        executer = new LogTaskThreadPoolExecuter();
        this.preprocessedEvents = new ArrayList<LogEvent>();

    }

    private static List<LogEvent> sortLogs(List<LogEvent> logEvents, int left, int right) {
        if (left < right) {
            int initialPivot = left + ((right - left) / 2);
            int pivot = partition(logEvents, left, right, initialPivot);
            if (pivot > 0) {
                sortLogs(logEvents, left, pivot - 1);
            } else if (pivot < (logEvents.size() - 1)) {
                sortLogs(logEvents, pivot + 1, right);
            }
        }
        return logEvents;
    }

    private synchronized static int partition(List<LogEvent> logEvents, int left, int right, int pivot) {
        int storeIndex;
        long logTime = createDateObject(logEvents.get(pivot).getLogTime()).getTime();
        LogEvent logEvent = logEvents.get(right);
        logEvents.set(right, logEvents.get(pivot));
        logEvents.set(pivot, logEvent);
        storeIndex = left;
        for (int i = left; i < right; i++) {
            long t1 = createDateObject(logEvents.get(i).getLogTime()).getTime();
            if (t1 > logTime) {
                logEvent = logEvents.get(storeIndex);
                logEvents.set(storeIndex, logEvents.get(i));
                logEvents.set(i, logEvent);
                storeIndex = storeIndex + 1;
            }
        }
        logEvent = logEvents.get(storeIndex);
        logEvents.set(storeIndex, logEvents.get(right));
        logEvents.set(right, logEvent);
        return storeIndex;
    }

    private static Date createDateObject(String date) {
        Date d = null;
        DateFormat formatter;
        try {
            formatter = new SimpleDateFormat(LoggingConstants.DATE_TIME_FORMATTER);
            d = formatter.parse(date);
        } catch (ParseException e) {
            log.error("Illegal Date Format", e);
        }
        return d;
    }

    private List<LogEvent> getLogEvents() {
        return this.events;
    }

    private LogTaskThreadPoolExecuter getExecuter() {
        return executer;
    }

    public List<LogEvent> getPreprocessedEvents() {
        return preprocessedEvents;
    }

    @Override
    public List<LogEvent> call() throws Exception {
        List<LogEvent> logEvents;
        if (events != null) {
            logEvents = sortLogs(events, 0, events.size() - 1);

        } else {
            logEvents = new ArrayList<LogEvent>();
        }
        return logEvents;
    }

}<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/util/LoggingUtil.java
/*
 * Copyright 2005-2007 WSO2, Inc. (http://wso2.com)
 *
 * Licensed 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.wso2.carbon.logging.service.util;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.description.AxisService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.net.SyslogAppender;
import org.springframework.util.Log4jConfigurer;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.core.util.SystemFilter;
import org.wso2.carbon.logging.service.LogViewerException;
import org.wso2.carbon.logging.service.appender.CarbonMemoryAppender;
import org.wso2.carbon.logging.service.config.ServiceConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfiguration;
import org.wso2.carbon.logging.service.data.SyslogData;
import org.wso2.carbon.logging.service.internal.DataHolder;
import org.wso2.carbon.logging.service.internal.LoggingServiceComponent;
import org.wso2.carbon.logging.service.registry.RegistryManager;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.tenant.TenantManager;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.Pageable;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.logging.CircularBuffer;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class LoggingUtil {

    public static final String SYSTEM_LOG_PATTERN = "[%d] %5p - %x %m {%c}%n";
    private static final int MAX_LOG_MESSAGES = 200;
    private static final String CARBON_LOGFILE_APPENDER = "CARBON_LOGFILE";
    private static final Log log = LogFactory.getLog(LoggingUtil.class);
    private static RegistryManager registryManager = new RegistryManager();

    public static boolean isStratosService() throws Exception {
        String serviceName = ServerConfiguration.getInstance().getFirstProperty("ServerKey");
        return ServiceConfigManager.isStratosService(serviceName);
    }

    public static void setSystemLoggingParameters(String logLevel, String logPattern)
            throws Exception {
        registryManager.updateConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL, logLevel);
        registryManager
                .updateConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN, logPattern);
    }

    public static SyslogData getSyslogData() throws Exception {
        return registryManager.getSyslogData();
    }

    private static String[] getAdminServiceNames() {
        ConfigurationContext configurationContext = DataHolder.getInstance()
                .getServerConfigContext();
        Map<String, AxisService> services = configurationContext.getAxisConfiguration()
                .getServices();
        List<String> adminServices = new ArrayList<String>();
        for (Map.Entry<String, AxisService> entry : services.entrySet()) {
            AxisService axisService = entry.getValue();
            if (SystemFilter.isAdminService(axisService)
                    || SystemFilter.isHiddenService(axisService)) {
                adminServices.add(axisService.getName());
            }
        }
        return adminServices.toArray(new String[adminServices.size()]);
    }

    public static int getTenantIdForDomain(String tenantDomain) throws LogViewerException {
        int tenantId;
        TenantManager tenantManager = LoggingServiceComponent.getTenantManager();
        if (tenantDomain == null || tenantDomain.equals("")) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        } else {

            try {
                tenantId = tenantManager.getTenantId(tenantDomain);
            } catch (UserStoreException e) {
                throw new LogViewerException("Cannot find tenant id for the given tenant domain.");
            }
        }
        return tenantId;
    }

    public static boolean isValidTenant(String domain) {
        int tenantId;
        if (domain == null || domain.equals("")) {
            tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
        } else {
            try {
                tenantId = LoggingUtil.getTenantIdForDomain(domain);
            } catch (LogViewerException e) {
                return false;
            }
        }

        if (tenantId == org.wso2.carbon.base.MultitenantConstants.INVALID_TENANT_ID) {
            return false;
        }
        return true;
    }

    public static boolean isFileAppenderConfiguredForST() {
        Logger rootLogger = Logger.getRootLogger();
        DailyRollingFileAppender logger = (DailyRollingFileAppender) rootLogger
                .getAppender(CARBON_LOGFILE_APPENDER);
        if (logger != null
                && CarbonContext.getThreadLocalCarbonContext().getTenantId() == org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID) {
            return true;
        } else {
            return false;
        }
    }


    public static boolean isAdmingService(String serviceName) {
        String[] adminServices = getAdminServiceNames();
        for (String adminService : adminServices) {
            if (adminService.equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    public static String getSystemLogLevel() throws Exception {
        String systemLogLevel = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL);
        if (systemLogLevel == null) {
            return Logger.getRootLogger().getLevel().toString();
        }
        return systemLogLevel;
    }

    public static String getSystemLogPattern() throws Exception {
        String systemLogPattern = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN);
        if (systemLogPattern == null) {
            return LoggingUtil.SYSTEM_LOG_PATTERN;
        }
        return systemLogPattern;
    }

    public static boolean isValidTenantDomain(String tenantDomain) {
        try {
            getTenantIdForDomain(tenantDomain);
            return true;
        } catch (LogViewerException e) {
            return false;
        }
    }

    public static boolean isManager() {
        if (LoggingConstants.WSO2_STRATOS_MANAGER.equalsIgnoreCase(ServerConfiguration.getInstance()
                .getFirstProperty("ServerKey"))) {
            return true;
        } else {
            return false;
        }
    }

    public static void loadCustomConfiguration() throws Exception {
        // set the appender details

        // we have not provided a facility to add or remove appenders so all the
        // initial appender set should present in the system.
        // and all the initall logger should present in the system
        Set<Appender> appenderSet = new HashSet<Appender>();
        Logger rootLogger = LogManager.getRootLogger();

        // set the root logger level, if the system log level is changed.
        String persistedSystemLoggerLevel = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_LEVEL);
        boolean systemLogLevelChanged = (persistedSystemLoggerLevel != null);
        if (systemLogLevelChanged) {
            rootLogger.setLevel(Level.toLevel(persistedSystemLoggerLevel));
        }

        String persistedSystemLogPattern = registryManager
                .getConfigurationProperty(LoggingConstants.SYSTEM_LOG_PATTERN);
        boolean systemLogPatternChanged = (persistedSystemLogPattern != null);
        setSystemLoggingParameters(persistedSystemLoggerLevel,
                (systemLogPatternChanged) ? persistedSystemLogPattern : SYSTEM_LOG_PATTERN);

        addAppendersToSet(rootLogger.getAllAppenders(), appenderSet);

        // System log level has been changed, need to update all the loggers and
        // appenders
        if (systemLogLevelChanged) {
            Logger logger;
            Enumeration loggersEnum = LogManager.getCurrentLoggers();
            Level systemLevel = Level.toLevel(persistedSystemLoggerLevel);
            while (loggersEnum.hasMoreElements()) {
                logger = (Logger) loggersEnum.nextElement();
                // we ignore all class level defined loggers
                addAppendersToSet(logger.getAllAppenders(), appenderSet);
                logger.setLevel(systemLevel);
            }

            for (Appender appender : appenderSet) {
                if (appender instanceof AppenderSkeleton) {
                    AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                    appenderSkeleton.setThreshold(systemLevel);
                    appenderSkeleton.activateOptions();
                }
            }
        }

        // Update the logger data according to the data stored in the registry.
        Collection loggerCollection = registryManager.getLoggers();
        if (loggerCollection != null) {
            String[] loggerResourcePaths = loggerCollection.getChildren();
            for (String loggerResourcePath : loggerResourcePaths) {
                String loggerName = loggerResourcePath.substring(LoggingConstants.LOGGERS.length());
                Logger logger = LogManager.getLogger(loggerName);
                Resource loggerResource = registryManager.getLogger(loggerName);
                if (loggerResource != null && logger != null) {
                    logger.setLevel(Level.toLevel(loggerResource
                            .getProperty(LoggingConstants.LoggerProperties.LOG_LEVEL)));
                    logger.setAdditivity(Boolean.parseBoolean(loggerResource
                            .getProperty(LoggingConstants.LoggerProperties.ADDITIVITY)));
                }
            }
        }

        // update the appender data according to data stored in database
        Collection appenderCollection = registryManager.getAppenders();
        if (appenderCollection != null) {
            String[] appenderResourcePaths = appenderCollection.getChildren();
            for (String appenderResourcePath : appenderResourcePaths) {
                String appenderName = appenderResourcePath.substring(LoggingConstants.APPENDERS
                        .length());
                Appender appender = getAppenderFromSet(appenderSet, appenderName);
                Resource appenderResource = registryManager.getAppender(appenderName);
                if (appenderResource != null && appender != null) {
                    if ((appender.getLayout() != null)
                            && (appender.getLayout() instanceof PatternLayout)) {
                        ((PatternLayout) appender.getLayout())
                                .setConversionPattern(appenderResource
                                        .getProperty(LoggingConstants.AppenderProperties.PATTERN));
                    }
                    if (appender instanceof FileAppender) {
                        FileAppender fileAppender = ((FileAppender) appender);

                        // resolves the log file path, if not absolute path, calculate with CARBON_HOME as the base
                        Path logFilePath = Paths.get(appenderResource.getProperty(
                                LoggingConstants.AppenderProperties.LOG_FILE_NAME));
                        if (!logFilePath.isAbsolute()) {
                            logFilePath = Paths.get(System.getProperty(ServerConstants.CARBON_HOME)).resolve(logFilePath);
                        }
                        fileAppender.setFile(logFilePath.normalize().toString());
                        fileAppender.activateOptions();
                    }

                    if (appender instanceof CarbonMemoryAppender) {
                        CarbonMemoryAppender memoryAppender = (CarbonMemoryAppender) appender;
                        memoryAppender.setCircularBuffer(new CircularBuffer(200));
                        memoryAppender.activateOptions();
                    }

                    if (appender instanceof SyslogAppender) {
                        SyslogAppender syslogAppender = (SyslogAppender) appender;
                        syslogAppender.setSyslogHost(appenderResource
                                .getProperty(LoggingConstants.AppenderProperties.SYS_LOG_HOST));
                        syslogAppender.setFacility(appenderResource
                                .getProperty(LoggingConstants.AppenderProperties.FACILITY));
                    }

                    if (appender instanceof AppenderSkeleton) {
                        AppenderSkeleton appenderSkeleton = (AppenderSkeleton) appender;
                        appenderSkeleton.setThreshold(Level.toLevel(appenderResource
                                .getProperty(LoggingConstants.AppenderProperties.THRESHOLD)));
                        appenderSkeleton.activateOptions();
                    }
                }
            }
        }
    }


    private static void addAppendersToSet(Enumeration appenders, Set<Appender> appenderSet) {
        while (appenders.hasMoreElements()) {
            Appender appender = (Appender) appenders.nextElement();
            appenderSet.add(appender);
        }
    }

    public static Appender getAppenderFromSet(Set<Appender> appenderSet, String name) {
        for (Appender appender : appenderSet) {
            if ((appender.getName() != null) && (appender.getName().equals(name))) {
                return appender;
            }
        }
        return null;
    }

    public static void updateConfigurationProperty(String key, String value)
            throws RegistryException {
        registryManager.updateConfigurationProperty(key, value);
    }

    public static String getConfigurationProperty(String key) throws RegistryException {
        return registryManager.getConfigurationProperty(key);
    }

    public static void removeAllLoggersAndAppenders() throws Exception {
        registryManager.removeAllRegistryEntries();
    }

    public static boolean isSysLogAppender(String tenantDomain) throws Exception {
        SyslogConfiguration syslogConfig = SyslogConfigManager.loadSyslogConfiguration();
        return syslogConfig.isSyslogOn();
    }

    public static boolean isSyslogConfigured() throws Exception {
        if (registryManager.getSyslogConfig() == null) {
            return false;
        } else {
            return true;
        }
    }

    public static int getLineNumbers(String logFile) throws Exception {
        InputStream logStream;

        try {
            logStream = getLocalInputStream(logFile);
        } catch (IOException e) {
            throw new LogViewerException("Cannot find the specified file location to the log file",
                    e);
        } catch (Exception e) {
            throw new LogViewerException("Cannot find the specified file location to the log file",
                    e);
        }
        try {
            byte[] c = new byte[1024];
            int count = 0;
            int readChars = 0;
            while ((readChars = logStream.read(c)) != -1) {
                for (int i = 0; i < readChars; ++i) {
                    if (c[i] == '\n') {
                        ++count;
                    }
                }
            }
            return count;
        } catch (IOException e) {
            throw new LogViewerException("Cannot read file size from the " + logFile, e);
        } finally {
            try {
                logStream.close();
            } catch (IOException e) {
                throw new LogViewerException("Cannot close the input stream " + logFile, e);
            }
        }
    }

    public static String[] getLogLinesFromFile(String logFile, int maxLogs, int start, int end)
            throws LogViewerException {
        ArrayList<String> logsList = new ArrayList<String>();
        InputStream logStream;
        if (end > maxLogs) {
            end = maxLogs;
        }
        try {
            logStream = getLocalInputStream(logFile);
        } catch (Exception e) {
            throw new LogViewerException("Cannot find the specified file location to the log file",
                    e);
        }
        int index = 1;
        String line;
        try (BufferedReader dataInput = new BufferedReader(new InputStreamReader(logStream))) {
            while ((line = dataInput.readLine()) != null) {
                if (index <= end && index > start) {
                    logsList.add(line);
                }
                index++;
            }
        } catch (IOException e) {
            log.error("Cannot read the log file", e);
            throw new LogViewerException("Cannot read the log file", e);
        }
        return logsList.toArray(new String[logsList.size()]);
    }

    public static void restoreDefaults() throws Exception {
        registryManager.removeAllRegistryEntries();
        LogManager.resetConfiguration();

        try {
            String logFile = CarbonUtils.getCarbonConfigDirPath()
                    + RegistryConstants.PATH_SEPARATOR + "log4j.properties";
            Log4jConfigurer.initLogging(logFile);
        } catch (FileNotFoundException e) {
            String msg = "Cannot restore default logging configuration."
                    + " log4j.properties file is not found in the classpath";
            throw new LogViewerException(msg, e);
        }
    }

    private static InputStream getLocalInputStream(String logFile) throws FileNotFoundException, LogViewerException {
        Path logFilePath = Paths.get(CarbonUtils.getCarbonLogsPath(), logFile);

        if (!isPathInsideBaseDirectory(Paths.get(CarbonUtils.getCarbonLogsPath()), logFilePath)) {
            throw new LogViewerException("Specified log file path is outside carbon logs directory.");
        }

        FileAppender carbonLogFileAppender = (FileAppender) Logger.getRootLogger().getAppender(CARBON_LOGFILE_APPENDER);
        String carbonLogFileName = new File(carbonLogFileAppender.getFile()).getName();

        if (!logFilePath.getFileName().toString().startsWith(carbonLogFileName)) {
            throw new LogViewerException("Trying to access logs other than CARBON_LOGFILE appender log file.");
        }

        InputStream is = new BufferedInputStream(new FileInputStream(logFilePath.toString()));
        return is;
    }

    /**
     * This method stream log messages and retrieve 100 log messages per page
     *
     * @param pageNumber The page required. Page number starts with 0.
     * @param sourceList The original list of items
     * @param pageable   The type of Pageable item
     * @return Returned page
     */
    public static <C> List<C> doPaging(int pageNumber, List<C> sourceList, int maxLines,
                                       Pageable pageable) {
        if (pageNumber < 0 || pageNumber == Integer.MAX_VALUE) {
            pageNumber = 0;
        }
        if (sourceList.size() == 0) {
            return sourceList;
        }
        if (pageNumber < 0) {
            throw new RuntimeException("Page number should be a positive integer. "
                    + "Page numbers begin at 0.");
        }
        int itemsPerPageInt = MAX_LOG_MESSAGES; // the default number of item
        // per page
        int numberOfPages = (int) Math.ceil((double) maxLines / itemsPerPageInt);
        if (pageNumber > numberOfPages - 1) {
            pageNumber = numberOfPages - 1;
        }
        List<C> returnList = new ArrayList<C>();
        for (int i = 0; i < sourceList.size(); i++) {
            returnList.add(sourceList.get(i));
        }
        int pages = calculatePageLevel(pageNumber + 1);
        if (pages > numberOfPages) {
            pages = numberOfPages;
        }
        pageable.setNumberOfPages(pages);
        pageable.set(returnList);
        return returnList;
    }

    /*
     * This is an equation to retrieve the visible number of pages ie p1-p5 -> 5
     * p6-p10 -> 10 p11-p15 -> 15
     */
    private static int calculatePageLevel(int x) {
        int p = x / 5;
        int q = x % 5;
        int t = (p + 1) * 5;
        int s = (p * 5) + 1;
        int y = q > 0 ? t : s;
        return y;
    }

    /**
     * Tests if the provided path is inside the base directory path.
     *
     * @param baseDirPath absolute {@link Path} of the base directory in which we want to check whether the given path
     *                    is inside
     * @param path        {@link Path} to be tested
     * @return {@code true} if the given path is inside the base directory path, otherwise {@code false}
     */
    private static boolean isPathInsideBaseDirectory(Path baseDirPath, Path path) {
        Path resolvedPath = baseDirPath.resolve(path).normalize();
        return resolvedPath.startsWith(baseDirPath.normalize());
    }
}

<file_sep>/components/reporting/org.wso2.carbon.reporting.core/src/main/java/org/wso2/carbon/reporting/core/internal/ReportingComponent.java
/**
 * Copyright (c) 2009, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * Licensed 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.wso2.carbon.reporting.core.internal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.registry.core.exceptions.RegistryException;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.reporting.core.utils.CommonUtil;
import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;


/**
 * @scr.component name="reporting.services" immediate="true"
 * @scr.reference name="registry.service" interface="org.wso2.carbon.registry.core.service.RegistryService"
 * cardinality="1..1" policy="dynamic"  bind="setRegistryService" unbind="unsetRegistryService"
 * @scr.reference name="org.wso2.carbon.ndatasource.core.DataSourceService" interface="org.wso2.carbon.ndatasource.core.DataSourceService"
 * cardinality="0..1" policy="dynamic" bind="setCarbonDataSourceService" unbind="unsetCarbonDataSourceService"
 */

public class ReportingComponent {
    private static Log log = LogFactory.getLog(ReportingComponent.class);
    private static RegistryService registryServiceInstance;
    private static DataSourceService dataSourceService1;


    protected void activate(ComponentContext componentContext) {
        try {
            PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
            carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
            carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);

            ReportingAxis2ConfigurationContextObserver observer =
                    new ReportingAxis2ConfigurationContextObserver();
            componentContext.getBundleContext().
                    registerService(Axis2ConfigurationContextObserver.class.getName(), observer, null);
            CommonUtil.addJrxmlConfigs(registryServiceInstance.getSystemRegistry());
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
        }

    }

    protected void deactivate(ComponentContext componentContext) {
        log.debug("report definition  deactivated");
    }

    protected void setRegistryService(RegistryService registryService) {
        registryServiceInstance = registryService;
    }

    protected void unsetRegistryService(RegistryService registryService) {
        registryServiceInstance = null;
    }


    public static RegistryService getRegistryService() throws RegistryException {
        if (registryServiceInstance == null) {
            throw new RegistryException("Registry Service instance null");
        }
        return registryServiceInstance;
    }

    protected void setCarbonDataSourceService(
            DataSourceService dataSourceService) {
        if (log.isDebugEnabled()) {
            log.debug("Setting the Carbon Data Sources Service");
        }
        ReportingComponent.dataSourceService1 = dataSourceService;
    }

    protected void unsetCarbonDataSourceService(
            DataSourceService dataSourceService) {
        dataSourceService1 = dataSourceService;
    }

    public static DataSourceService getCarbonDataSourceService() {
        return dataSourceService1;
    }

}<file_sep>/components/logging/org.wso2.carbon.logging.summarizer/src/main/java/org/wso2/carbon/logging/summarizer/utils/LoggingConfigManager.java
/*
 * Copyright The Apache Software Foundation.
 *
 * Licensed 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.
 */
// TOD0 Change the packaging to org.wso2.carbon.logging.common

package org.wso2.carbon.logging.summarizer.utils;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.utils.CarbonUtils;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

public class LoggingConfigManager {

    private static final Log log = LogFactory.getLog(LoggingConfigManager.class);
    private static LoggingConfigManager cassandraConfig;
    private static BundleContext bundleContext;

    public static LoggingConfigManager getCassandraConfig() {
        return cassandraConfig;
    }

    public static void setBundleContext(BundleContext bundleContext) {
        LoggingConfigManager.bundleContext = bundleContext;
    }

    public static void setCassandraConfig(LoggingConfigManager syslogConfig) {
        LoggingConfigManager.cassandraConfig = syslogConfig;
    }

    public static Log getLog() {
        return log;
    }

    public LoggingConfig getSyslogData() {
        return null;
    }

    /**
     * Returns the configurations from the Cassandra configuration file.
     *
     * @return cassandra configurations
     */
    public static LoggingConfig loadLoggingConfiguration() {
        // gets the configuration file name from the cassandra-config.xml.
        String cassandraConfigFileName = CarbonUtils.getCarbonConfigDirPath()
                + RegistryConstants.PATH_SEPARATOR
                + LoggingConstants.ETC_DIR
                + RegistryConstants.PATH_SEPARATOR
                + LoggingConstants.LOGGING_CONF_FILE;
        return loadLoggingConfiguration(cassandraConfigFileName);
    }

    private InputStream getInputStream(String configFilename)
            throws IOException {
        InputStream inStream = null;
        File configFile = new File(configFilename);
        if (configFile.exists()) {
            inStream = new FileInputStream(configFile);
        }
        String warningMessage = "";
        if (inStream == null) {
            URL url;
            if (bundleContext != null) {
                if ((url = bundleContext.getBundle().getResource(
                        LoggingConstants.LOGGING_CONF_FILE)) != null) {
                    inStream = url.openStream();
                } else {
                    warningMessage = "Bundle context could not find resource "
                            + LoggingConstants.LOGGING_CONF_FILE
                            + " or user does not have sufficient permission to access the resource.";
                    log.warn(warningMessage);
                }

            } else {
                if ((url = this.getClass().getClassLoader()
                        .getResource(LoggingConstants.LOGGING_CONF_FILE)) != null) {
                    inStream = url.openStream();
                } else {
                    warningMessage = "Could not find resource "
                            + LoggingConstants.LOGGING_CONF_FILE
                            + " or user does not have sufficient permission to access the resource.";
                    log.warn(warningMessage);
                }
            }
        }
        return inStream;
    }


    private static LoggingConfig loadDefaultConfiguration() {
        LoggingConfig config = new LoggingConfig();
        config.setCassandraServerAvailable(false);
        return config;
    }

    /**
     * Loads the given logging Configuration file.
     *
     * @param configFilename Name of the configuration file
     * @return the syslog configuration data.
     */
    private static LoggingConfig loadLoggingConfiguration(
            String configFilename) {
        LoggingConfig config = new LoggingConfig();
        InputStream inputStream = null;
        try {
            inputStream = new LoggingConfigManager()
                    .getInputStream(configFilename);
        } catch (IOException e1) {
            log.error("Could not close the Configuration File "
                    + configFilename);
        }
        if (inputStream != null) {
            try {
                XMLStreamReader parser = XMLInputFactory.newInstance()
                        .createXMLStreamReader(inputStream);
                StAXOMBuilder builder = new StAXOMBuilder(parser);
                OMElement documentElement = builder.getDocumentElement();
                @SuppressWarnings("rawtypes")
                Iterator it = documentElement.getChildElements();
                while (it.hasNext()) {
                    OMElement element = (OMElement) it.next();
                    // Checks whether logging configuration enable.
                    if (LoggingConstants.CassandraConfigProperties.IS_CASSANDRA_AVAILABLE
                            .equals(element.getLocalName())) {
                        String isCassandraOn = element.getText();
                        // by default, make the loggingConfig off.
                        boolean isCassandraAvailable = false;
                        if (isCassandraOn.trim().equalsIgnoreCase("true")) {
                            isCassandraAvailable = true;
                        }
                        config.setCassandraServerAvailable(isCassandraAvailable);
                    }if (LoggingConstants.CassandraConfigProperties.IS_DELETE_COL_FAMILY
                            .equals(element.getLocalName())) {
                        String isDeleteColFamily = element.getText();
                        // by default, make the loggingConfig off.
                        boolean isDeleteColumnFamily = false;
                        if (isDeleteColFamily.trim().equalsIgnoreCase("true")) {
                            isDeleteColumnFamily = true;
                        }
                        config.setDeleteColFamily(isDeleteColumnFamily);
                    } else if (LoggingConstants.CassandraConfigProperties.USER_NAME
                            .equals(element.getLocalName())) {
                        config.setCassUsername(element.getText());
                    } else if (LoggingConstants.CassandraConfigProperties.PASSWORD
                            .equals(element.getLocalName())) {
                        config.setCassPassword(element.getText());
                    } else if (LoggingConstants.CassandraConfigProperties.CONSISTENCY_LEVEL
                            .equals(element.getLocalName())) {
                        config.setConsistencyLevel(element.getText());
                    } else if (LoggingConstants.CassandraConfigProperties.AUTO_DISCOVERY
                            .equals(element.getLocalName())) {

                        String autoDiscoveryEnable = element.getAttributeValue(
                                new QName(LoggingConstants.CassandraConfigProperties.AUTO_DISCOVERY_ENABLE));
                        boolean isAutoDiscoveryEnable = false;
                        if (autoDiscoveryEnable.trim().equalsIgnoreCase("true")) {
                            isAutoDiscoveryEnable = true;
                        }
                        config.setAutoDiscoveryEnable(isAutoDiscoveryEnable);

                        String delay = element.getAttributeValue(
                                new QName(LoggingConstants.CassandraConfigProperties.AUTO_DISCOVERY_DELAY));
                        if (delay != null && !"".equals(delay.trim())) {
                            int delayAsInt = -1;
                            try {
                                delayAsInt = Integer.parseInt(delay.trim());
                            } catch (NumberFormatException ignored) {
                            }
                            if (delayAsInt > 0) {
                                config.setAutoDiscoveryDelay(delayAsInt);
                            }
                        }
                    } else if (LoggingConstants.CassandraConfigProperties.RETRY_DOWNED_HOSTS
                            .equals(element.getLocalName())) {

                        String retryDownedEnable = element.getAttributeValue(
                                new QName(LoggingConstants.CassandraConfigProperties.RETRY_DOWNED_HOSTS_ENABLE));
                        boolean isRetryDownedHostsEnable = false;
                        if (retryDownedEnable.trim().equalsIgnoreCase("true")) {
                            isRetryDownedHostsEnable = true;
                        }
                        config.setRetryDownedHostsEnable(isRetryDownedHostsEnable);

                        String queue = element.getAttributeValue(
                                new QName(LoggingConstants.CassandraConfigProperties.RETRY_DOWNED_HOSTS_QUEUE));
                        if (queue != null && !"".equals(queue.trim())) {
                            int queueAsInt = -1;
                            try {
                                queueAsInt = Integer.parseInt(queue.trim());
                            } catch (NumberFormatException ignored) {
                            }
                            if (queueAsInt > 0) {
                                config.setRetryDownedHostsQueueSize(queueAsInt);
                            }
                        }
                    } else if (LoggingConstants.CassandraConfigProperties.PUBLISHER_URL
                            .equals(element.getLocalName())) {
                        config.setPublisherURL(element.getText());
                    } else if (LoggingConstants.CassandraConfigProperties.PUBLISHER_USER
                            .equals(element.getLocalName())) {
                        config.setPublisherUser(element.getText());
                    } else if (LoggingConstants.CassandraConfigProperties.PUBLISHER_PASSWORD
                            .equals(element.getLocalName())) {
                        config.setPublisherPassword(element.getText());
                    } else if (LoggingConstants.CassandraConfigProperties.CRON_EXPRESSION
                            .equals(element.getLocalName())) {
                        config.setCronExpression(element.getText());
                    } else if (LoggingConstants.CassandraConfigProperties.HIVE_QUERY
                            .equals(element.getLocalName())) {
                        config.setHiveQuery(element.getText());
                    }
                    else if (LoggingConstants.CassandraConfigProperties.LOG_DIRECTORY
                            .equals(element.getLocalName())) {
                        config.setLogDirectory(element.getText());
                    }
                     else if (LoggingConstants.CassandraConfigProperties.TMP_LOG_DIRECTORY
                            .equals(element.getLocalName())) {
                        config.setTmpLogsDirectory(element.getText());
                    }
                    else if (LoggingConstants.CassandraConfigProperties.CASSANDRA_HOST
                            .equals(element.getLocalName())) {
                        config.setCassandraHost(element.getText());
                    }
                     else if (LoggingConstants.BamProperties.BAM_USERNAME
                            .equals(element.getLocalName())) {
                        config.setBamUserName(element.getText());
                    }
                     else if (LoggingConstants.BamProperties.BAM_PASSWORD
                            .equals(element.getLocalName())) {
                        config.setBamPassword(element.getText());
                    }
                    else if (LoggingConstants.HdfsProperties.HDFS_CONFIG
                            .equals(element.getLocalName())) {
                        config.setHdfsConfig(element.getText());
                    }
                    else if (LoggingConstants.HdfsProperties.ARCHIVED_LOG_LOCATION
                            .equals(element.getLocalName())) {
                        config.setArchivedLogLocation(element.getText());
                    }
                }
                //setting the default valus to config
                config.setColFamily("log");
                config.setCluster("admin");
                config.setKeyspace("EVENT_KS");
                return config;
            } catch (Exception
                    e) {
                String msg = "Error in loading Stratos Configurations File: "
                        + configFilename + ". Default Settings will be used.";
                log.error(msg, e);
                return loadDefaultConfiguration(); // returns the default
                // configurations, if the
                // file could not be loaded.
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.error("Could not close the Configuration File "
                                + configFilename);
                    }
                }
            }
        }

        log.error("Unable to locate the stratos configurations file. "
                + "Default Settings will be used.");
        return

                loadDefaultConfiguration(); // return the default configurations,
        // if the file not found.
    }
}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/config/ServiceConfigManager.java
/*
 * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org
 * Licensed 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.wso2.carbon.logging.service.config;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.logging.service.LogViewerException;
import org.wso2.carbon.logging.service.util.LoggingConstants;
import org.wso2.carbon.utils.CarbonUtils;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ServiceConfigManager {

    private static final Log log = LogFactory.getLog(ServiceConfigManager.class);

    public static String[] getServiceNames() throws LogViewerException {
        String configFileName = CarbonUtils.getCarbonConfigDirPath() + File.separator +
                                LoggingConstants.MULTITENANCY_CONFIG_FOLDER + File.separator +
                                LoggingConstants.CONFIG_FILENAME;
        List<String> serviceNames = new ArrayList<String>();
        File configFile = new File(configFileName);
        if (configFile.exists()) {
            FileInputStream inputStream = null;
            try {
                inputStream = new FileInputStream(configFile);
                XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(
                        inputStream);
                StAXOMBuilder builder = new StAXOMBuilder(parser);
                OMElement documentElement = builder.getDocumentElement();
                @SuppressWarnings("unchecked")
                Iterator<OMElement> properties = documentElement.getChildrenWithName(new QName(
                        "cloudService"));
                while (properties.hasNext()) {
                    OMElement element = properties.next();
                    Iterator<OMElement> child = element.getChildElements();
                    while (child.hasNext()) {
                        OMElement element1 = (OMElement) child.next();
                        if ("key".equalsIgnoreCase(element1.getLocalName())) {
                            serviceNames.add(element1.getText());
                        }
                    }
                }
            } catch (Exception e) {
                String msg = "Error in loading Stratos Configurations File: " + configFileName;
                throw new LogViewerException(msg, e);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.error("Could not close the Configuration File " + configFileName, e);
                    }
                }
            }
        }
        return serviceNames.toArray(new String[serviceNames.size()]);
    }

    public static boolean isStratosService(String serviceName) throws LogViewerException {
        String services[] = getServiceNames();
        for (String service : services) {
            if (service.equals(serviceName)) {
                return true;
            }
        }
        return false;
    }
}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/test/java/org/wso2/carbon/logging/service/util/LoggingUtilTest.java
/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. 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.wso2.carbon.logging.service.util;

import org.apache.log4j.Appender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.SimpleLayout;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Unit tests for logging utils.
 */
public class LoggingUtilTest {

    private static final String APPENDER_NAME = "SIMPLE_APPENDER";

    @Test(groups = {"org.wso2.carbon.logging.service.util"},
            description = "Tests whether the Appender with the specified name is returned from " +
                    "LoggingUtil.getAppenderFromSet method given that the Appender set contains an appender " +
                    "without a name.")
    public void testGettingAppenderFromAppenderSet() {
        Appender appenderWithoutName = new ConsoleAppender(new SimpleLayout());

        Appender appenderWithName = new ConsoleAppender(new SimpleLayout());
        appenderWithName.setName(APPENDER_NAME);

        Set<Appender> appenderSet = new LinkedHashSet<>();
        appenderSet.add(appenderWithoutName);
        appenderSet.add(appenderWithName);

        Assert.assertEquals(appenderWithName, LoggingUtil.getAppenderFromSet(appenderSet, APPENDER_NAME),
                "Appender with the name " + APPENDER_NAME + " is not returned from getAppenderFromSet method.");
    }

}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/config/LoggingConfigManager.java
/*
 * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org
 * Licensed 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.wso2.carbon.logging.service.config;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.wso2.carbon.logging.service.LoggingConfigReaderException;
import org.wso2.carbon.logging.service.data.LoggingConfig;
import org.wso2.carbon.logging.service.util.LoggingConstants;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;

/***
 * This class is used to read the logging configurations from the configuration file.
 * eg file: <CARBON_SERVER>/repository/conf/etc/logging-config.xml
 */
public class LoggingConfigManager {

    private static final Log log = LogFactory.getLog(LoggingConfigManager.class);
    private static BundleContext bundleContext;

    public static void setBundleContext(BundleContext bundleContext) {
        LoggingConfigManager.bundleContext = bundleContext;
    }

    /**
     * Loads the given logging configuration file.
     *
     * @param configFilenameWithPath
     *         Name of the configuration file
     * @return the syslog configuration data. An empty configuration will be returned, if there any
     * issue while loading configurations.
     */
    public static LoggingConfig loadLoggingConfiguration(String configFilenameWithPath)
            throws IOException, XMLStreamException, LoggingConfigReaderException {
        InputStream inputStream;
        LoggingConfig config = new LoggingConfig();
        inputStream = new LoggingConfigManager().getInputStream(configFilenameWithPath);
        if (inputStream != null) {
            try {
                XMLStreamReader parser = XMLInputFactory.newInstance()
                                                        .createXMLStreamReader(inputStream);
                StAXOMBuilder builder = new StAXOMBuilder(parser);
                OMElement documentElement = builder.getDocumentElement();
                // load log provider configurations
                OMElement logProviderConfig = documentElement.getFirstChildWithName(
                        getQName(LoggingConstants.LogConfigProperties.LOG_PROVIDER_CONFIG));
                config = loadLogProviderProperties(config, logProviderConfig);
                // load log file provider configurations
                OMElement logFileProviderConfig = documentElement.getFirstChildWithName(
                        getQName(LoggingConstants.LogConfigProperties.LOG_FILE_PROVIDER_CONFIG));
                config = loadLogFileProviderProperties(config, logFileProviderConfig);
            } finally {
                if (inputStream != null) {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        log.error("Could not close the logging configuration file "
                                  + configFilenameWithPath, e);
                    }
                }
            }
        }
        return config;
    }

    /**
     * Load log file provider configs from the logging-config xml file.
     *
     * @param config
     *         - logging config which will be injected with config information
     * @param logFileProviderConfig
     *         - OM Element containing from the xml file
     * @return - logging config with injected LogFileProvider data
     * @throws LoggingConfigReaderException
     *         - if an error occured while parsing the xml file.
     */
    private static LoggingConfig loadLogFileProviderProperties(LoggingConfig config,
                                                               OMElement logFileProviderConfig)
            throws LoggingConfigReaderException {
        String implClass = logFileProviderConfig.getAttributeValue(
                new QName("", LoggingConstants.LogConfigProperties.CLASS_ATTRIBUTE));
        if (implClass != null) {
            config.setLogFileProviderImplClassName(implClass);
            OMElement propertiesElement = logFileProviderConfig.getFirstChildWithName(
                    getQName(LoggingConstants.LogConfigProperties.PROPERTIES));
            if (propertiesElement != null) {
                Object nextElement;
                OMElement propertyElement;
                // iterate through each property element in the xml file and add (name, value)
                // to the map within the LoggingConfig object for LogProvider properties.
                for (Iterator it = propertiesElement.getChildrenWithLocalName(
                        LoggingConstants.LogConfigProperties.PROPERTY); it.hasNext(); ) {
                    nextElement = it.next();
                    if (nextElement instanceof OMElement) {
                        propertyElement = (OMElement) nextElement;
                        config.setLogFileProviderProperty(
                                propertyElement.getAttributeValue(new QName(
                                        LoggingConstants.LogConfigProperties.PROPERTY_NAME)),
                                propertyElement.getAttributeValue(new QName(
                                        LoggingConstants.LogConfigProperties.PROPERTY_VALUE)));
                    }
                }
            } else {
                String msg = "Error loading log file provider properties for " + implClass +
                             " Check the logging configuration file";
                throw new LoggingConfigReaderException(msg);
            }
        } else {
            String msg = "LogFileProvider implementation class name is null, " +
                         "check the logging configuration file";
            throw new LoggingConfigReaderException(msg);
        }
        return config;
    }

    /**
     * Load log provider configs from the logging-config xml file.
     *
     * @param config
     *         - logging config which will be injected with config information
     * @param logProviderConfig
     *         - OM Element containing from the xml file
     * @return - logging config with injected LogProvider data
     * @throws LoggingConfigReaderException
     *         - if an error occured while parsing the xml file.
     */
    private static LoggingConfig loadLogProviderProperties(LoggingConfig config,
                                                           OMElement logProviderConfig)
            throws LoggingConfigReaderException {
        String implClass = logProviderConfig.getAttributeValue(
                new QName("", LoggingConstants.LogConfigProperties.CLASS_ATTRIBUTE));
        if (implClass != null) {
            config.setLogProviderImplClassName(implClass);
            // load log provider configuration
            OMElement propertiesElement = logProviderConfig.getFirstChildWithName(
                    getQName(LoggingConstants.LogConfigProperties.PROPERTIES));
            if (propertiesElement != null) {
                OMElement propertyElement;
                Object nextElement;
                // iterate through each property element in the xml file and add (name, value)
                // to the map within the LoggingConfig object for LogFileProvider properties.
                for (Iterator it = propertiesElement.getChildrenWithLocalName(
                        LoggingConstants.LogConfigProperties.PROPERTY); it.hasNext(); ) {
                    nextElement = it.next();
                    if (nextElement instanceof OMElement) {
                        propertyElement = (OMElement) nextElement;
                        config.setLogProviderProperty(
                                propertyElement.getAttributeValue(new QName(
                                        LoggingConstants.LogConfigProperties.PROPERTY_NAME)),
                                propertyElement.getAttributeValue(new QName(
                                        LoggingConstants.LogConfigProperties.PROPERTY_VALUE)));
                    }
                }
            } else {
                String msg = "Error loading log provider properties for " + implClass +
                             " Check the logging configuration file ";
                throw new LoggingConfigReaderException(msg);
            }
        } else {
            String msg = "LogProvider implementation class name is null, " +
                         "Check the loggging configuration file";
            throw new LoggingConfigReaderException(msg);
        }
        return config;
    }

    private static QName getQName(String localName) {
        return new QName(LoggingConstants.LogConfigProperties.DEFAULT_LOGGING_CONFIG_NAMESPACE,
                         localName);
    }

    /**
     * Get an input stream to read the file after loading the logging-config file.
     *
     * @param configFilename
     *         - configuration file name
     * @return - an input stream to the file
     * @throws IOException
     *         - if the file could not be opened
     */
    private InputStream getInputStream(String configFilename)
            throws IOException {
        InputStream inputStream = null;
        File configFile = new File(configFilename);
        if (configFile.exists()) {
            inputStream = new FileInputStream(configFile);
        }
        String warningMessage;
        if (inputStream == null) {
            URL url;
            if (bundleContext != null) {
                if ((url = bundleContext.getBundle().getResource(
                        LoggingConstants.LOGGING_CONF_FILE)) != null) {
                    inputStream = url.openStream();
                } else {
                    warningMessage = "Bundle context could not find resource "
                                     + LoggingConstants.LOGGING_CONF_FILE
                                     + " or user does not have sufficient permission to access " +
                                     "the resource.";
                    log.warn(warningMessage);
                }

            } else {
                if ((url = this.getClass().getClassLoader()
                               .getResource(LoggingConstants.LOGGING_CONF_FILE)) != null) {
                    inputStream = url.openStream();
                } else {
                    warningMessage = "Could not find resource "
                                     + LoggingConstants.LOGGING_CONF_FILE
                                     + " or user does not have sufficient permission to access " +
                                     "the resource.";
                    log.warn(warningMessage);
                }
            }
        }
        return inputStream;
    }
}
<file_sep>/components/logging/org.wso2.carbon.logging.admin.ui/src/main/resources/org/wso2/carbon/logging/admin/ui/i18n/Resources.properties
log-admin.logs=Logging
logger=Logger
parent.logger=Parent Logger
effective.level=Level
additivity=Additivity
true=True
false=False
logging.configuration=Logging Configuration
persist.all.configuration.changes=Persist All Configuration Changes
global.log4j.configuration=Global Log4J Configuration
log.level=Log Level
log.pattern=Log Pattern
syslog.porperty.configuration= Syslog Property Configuration
syslog.log.url=Syslog-ng log host
port=Port
realm=Realm
user.name = User Name
password = <PASSWORD>
update=Update
restore.defaults=Restore Defaults
configure.log4j.loggers=Configure Log4J Loggers
filter.loggers.by=Filter Loggers by
starts.with=Starts With
contains=Contains
configure.log4j.appenders=Configure Log4J Appenders
name=Name
threshold=Threshold
log.file=Log File
sys.log.host=Sys Log Host
facility=Facility
global.log.update.confirm=Do you really want to globally update the logging configuration?
syslog.log.update.confirm=Do you really want to globally update the syslog configuration?
global.log.restore.confirm=Do you really want to restore the original logging configuration?
appender.log.update.confirm=Do you really want to update the appender configuration?
loading=Loading...
successfully.updated.logger=Successfully updated logger
successfully.updated.syslog.config=Successfully updated Syslog config
logger.update.failed=Logger update failed
syslog.config.update.failed=Syslog config update failed
successfully.updated.appender=Successfully updated appender
appender.update.failed=Appender update failed
no.loggers.found=No loggers satisfying the search criteria found
global.log4j.config.restored.successfully=Global Log4j Configuration is Restored Successfully
successfully.updated.gloable.log4j.configuration=Successfully updated Global Log4j Configuration
gloable.log4j.configuration.update.failed=Global Log4j Configuration update failed
successfully.restored.gloable.log4j.configuration=Successfully Restored Global Log4j Configuration
gloable.log4j.configuration.retore.failed=Restoring of Global Log4j Configuration is failed

<file_sep>/components/hostobjects/org.wso2.carbon.hostobjects.carbonutil/src/main/java/org/wso2/carbon/hostobjects/carbonutil/internal/CarbonHostObjectServiceComponent.java
package org.wso2.carbon.hostobjects.carbonutil.internal;

import org.wso2.carbon.user.core.service.RealmService;

/**
 * @scr.component name="org.wso2.carbon.hostobject.carbonutil" immediate="true"
 * @scr.reference name="user.realmservice.default"
 * interface="org.wso2.carbon.user.core.service.RealmService"
 * cardinality="1..1" policy="dynamic" bind="setRealmService" unbind="unsetRealmService"
 */
public class CarbonHostObjectServiceComponent {

	protected void setRealmService(RealmService realmService) {
		ServiceHodler.setRealmService(realmService);
    }

    protected void unsetRealmService(RealmService realmService) {
    	ServiceHodler.setRealmService(null);
    }
	
}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/sort/LogTaskThreadPoolExecuter.java
/*
 * Copyright 2005,2014 WSO2, Inc. http://www.wso2.org
 * Licensed 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.wso2.carbon.logging.service.sort;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class LogTaskThreadPoolExecuter {
    private static final Log log = LogFactory.getLog(LogTaskThreadPoolExecuter.class);
    private final ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(5);
    private ThreadPoolExecutor threadPool = null;
    private int poolSize = 5;
    private int maxPoolSize = 5;
    private long keepAliveTime = 10;

    public LogTaskThreadPoolExecuter() {
        threadPool = new ThreadPoolExecutor(poolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, queue);
    }

    public void runTask(Runnable task) {
        threadPool.execute(task);
        log.info("Task Count : " + queue.size());
    }
}<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/LogViewerException.java
/*
 * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 * 
 * WSO2 Inc. 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.wso2.carbon.logging.service;

public class LogViewerException extends Exception {

    public LogViewerException(String s) {
        super(s);
    }

    public LogViewerException(String s, Throwable e) {
        super(s, e);
    }

}
<file_sep>/components/logging/org.wso2.carbon.logging.view.ui/src/main/resources/org/wso2/carbon/logging/view/ui/i18n/Resources.properties
archived.logs=Show archived logs
adv.search=Show advanced search
max.exceed.message=Maximum Number of Log Retrieval for the Day Exceeded... Your latest logs will be omitted.
logsmenutext=System Logs
applogsmenutext=Application Logs
viewlogsmenutext=View Logs text
system.logs=System Logs
app.logs=Application Logs
system.logs.view = System Log View
view=View
download=Download
search.logs=Search Logs
file.size = File Size
clear.all=Clear All Logs
clear.all.log.message=Do you want to clear all the logs
no.logs=--- No log entries found. ---
invalid.tenant= --- Invalid tenant domain ---
file.name = File Name
date = Date
action = Action
log.tail = Log Tail
service.name = Service Name
log.head = Log Head
log.message = Log Message
log.type = Type
local.log.location.information = Logs are taken from the local file system.
remote.log.location.information = Logs are taken from the remote log hosted server.
log.head.help = Enter the number of log lines to be displayed from the top-down.
tenant.domain = Tenant Domain
return.rows = Return Rows
show.at.or.before = Show at or Between
advanced.properties = Advanced Properties
priority = Priority
keyword = Keyword
logger = Logger
application.name=Application Name
filter.system.logs=Filter System Logs
date.format=mm/dd/yyyy hh:mm 
date.example=(eg 2012-05-18 06:21:39) 
view.stack.trace=More
view.logs.within.the.past.thirty.mins=Logs taken within past thirty minutes.
view.logs.between=Logs taken between.
log.level=Level
current.time=Current Time Zone:

<file_sep>/components/url-mapper/org.wso2.carbon.url.mapper.clustermessage/src/main/java/org/wso2/carbon/url/mapper/clustermessage/internal/VirtualHostClusterServiceComponent.java
/*
*  Copyright (c), WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. 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.wso2.carbon.url.mapper.clustermessage.internal;

import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.transport.local.LocalTransportReceiver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.tomcat.api.CarbonTomcatService;
import org.wso2.carbon.url.mapper.clustermessage.util.DataHolder;
import org.wso2.carbon.utils.ConfigurationContextService;

/**
 * Service Component to sending cluster message
 * @scr.component name="org.wso2.carbon.url.mapper.clustermessage" immediate="true"
 * @scr.reference name="config.context.service"
 * interface="org.wso2.carbon.utils.ConfigurationContextService"
 * cardinality="1..1" policy="dynamic"  bind="setConfigurationContextService"
 * unbind="unsetConfigurationContextService"
 * @scr.reference name="tomcat.service.provider"
 * interface="org.wso2.carbon.tomcat.api.CarbonTomcatService"
 * cardinality="1..1" policy="dynamic" bind="setCarbonTomcatService"
 * unbind="unsetCarbonTomcatService"

 * */
public class VirtualHostClusterServiceComponent {
    private static Log log = LogFactory.getLog(VirtualHostClusterServiceComponent.class);


    protected void activate(ComponentContext context) {
        try {
            DataHolder.getInstance().registerRetrieverServices(context.getBundleContext());
            if(log.isDebugEnabled()){
                log.debug("******* Tenant Activity bundle is activated ******* ");
            }
        } catch (Throwable e) {
            log.error("******* Error in activating Tenant Activity bundle ******* ", e);
        }
    }

    protected void deactivate(ComponentContext context) {
        if (log.isDebugEnabled()) {
            log.debug("******* Tenant Activity is deactivated ******* ");
        }
    }

    protected void setConfigurationContextService(ConfigurationContextService ccService) {
        ConfigurationContext serverCtx = ccService.getServerConfigContext();
        AxisConfiguration serverConfig = serverCtx.getAxisConfiguration();
        LocalTransportReceiver.CONFIG_CONTEXT = new ConfigurationContext(serverConfig);
        LocalTransportReceiver.CONFIG_CONTEXT.setServicePath("services");
        LocalTransportReceiver.CONFIG_CONTEXT.setContextRoot("local:/");

        DataHolder.getInstance().setConfigurationContextService(ccService);
    }

    protected void unsetConfigurationContextService(ConfigurationContextService ccService) {
        DataHolder.getInstance().setConfigurationContextService(null);
    }

    protected void setCarbonTomcatService(CarbonTomcatService carbonTomcatService) {
        //keeping the carbonTomcatService in UrlMapperAdminService class
        DataHolder.getInstance().setCarbonTomcatService(carbonTomcatService);
    }

    protected void unsetCarbonTomcatService(CarbonTomcatService carbonTomcatService) {
        DataHolder.getInstance().setCarbonTomcatService(null);
    }

}
<file_sep>/components/logging/org.wso2.carbon.logging.service/src/main/java/org/wso2/carbon/logging/service/provider/FileLogProvider.java
/*
*  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. 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.wso2.carbon.logging.service.provider;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.logging.service.LogViewerException;
import org.wso2.carbon.logging.service.config.ServiceConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfigManager;
import org.wso2.carbon.logging.service.config.SyslogConfiguration;
import org.wso2.carbon.logging.service.data.LogFileInfo;
import org.wso2.carbon.logging.service.data.LoggingConfig;
import org.wso2.carbon.logging.service.data.SyslogData;
import org.wso2.carbon.logging.service.provider.api.LogFileProvider;
import org.wso2.carbon.logging.service.util.LoggingConstants;
import org.wso2.carbon.logging.service.util.LoggingUtil;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

import javax.activation.DataHandler;
import javax.mail.util.ByteArrayDataSource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class FileLogProvider implements LogFileProvider {
    private static final String APPLICATION_TYPE_ZIP = "application/zip";
    private static final String SERVER_KEY = "ServerKey";
    private static final String URL_ENCODED_SPACE_CHAR = "%20";
    private static final String CARBON_LOGFILE_APPENDER = "CARBON_LOGFILE";
    private static Log log = LogFactory.getLog(FileLogProvider.class);

    /**
     * Initialize the log provider by reading the property comes with logging configuration file
     * This will be called immediate after create new instance of LogProvider
     *
     * @param loggingConfig -
     */
    @Override
    public void init(LoggingConfig loggingConfig) {
        if(log.isDebugEnabled()){
            log.debug("FileLogProvider is initialized.");
        }
    }

    @Override
    public List<LogFileInfo> getLogFileInfoList(String tenantDomain, String serverKey) throws LogViewerException {
        String folderPath = CarbonUtils.getCarbonLogsPath();
        List<LogFileInfo> logs = new ArrayList<LogFileInfo>();
        LogFileInfo logFileInfo;
        String currentServerName = getCurrentServerName();
        if ((((tenantDomain == null || "".equals(tenantDomain)) && isSuperTenantUser()) ||
             (tenantDomain != null && MultitenantConstants.SUPER_TENANT_DOMAIN_NAME
                     .equalsIgnoreCase(tenantDomain))) &&
            (serverKey == null || "".equals(serverKey) || serverKey.equalsIgnoreCase(
                    currentServerName))) {

            File folder = new File(folderPath);
            FileFilter fileFilter = new WildcardFileFilter(LoggingConstants.RegexPatterns.LOCAL_CARBON_LOG_PATTERN);
            File[] listOfFiles = folder.listFiles(fileFilter);
            // folder.listFiles consumes lot of  memory when there are many files in the folder
            // (> 10 000), can be fixed with nio support in Java7
            if (listOfFiles == null) {
                // folder.listFiles can return a null, in that case return a default log info
                if (log.isDebugEnabled()) {
                    log.debug("List of log files of the given pattern is null.");
                }
                return getDefaultLogInfoList();
            }
            for (File file : listOfFiles) {
                String filename = file.getName();
                String[] fileDates = filename.split(LoggingConstants.RegexPatterns.LOG_FILE_DATE_SEPARATOR);
                String filePath = CarbonUtils.getCarbonLogsPath() + LoggingConstants.URL_SEPARATOR + filename;
                File logfile = new File(filePath);
                if (fileDates.length == 2) {
                    logFileInfo = new LogFileInfo(filename, fileDates[1], getFileSize(logfile));
                } else {
                    logFileInfo = new LogFileInfo(filename, LoggingConstants.RegexPatterns.CURRENT_LOG,
                            getFileSize(logfile));
                }
                logs.add(logFileInfo);
            }
        }
        return getSortedPerLogInfoList(logs);
    }

    @Override
    public DataHandler downloadLogFile(String logFile, String tenantDomain, String serverKey) throws LogViewerException {
        InputStream is = null;
        ByteArrayDataSource bytArrayDS;
        int tenantId = LoggingUtil.getTenantIdForDomain(tenantDomain);
        try {
            is = getInputStream(logFile, tenantId, serverKey);
            bytArrayDS = new ByteArrayDataSource(is, APPLICATION_TYPE_ZIP);
            return new DataHandler(bytArrayDS);
        } catch (LogViewerException e) {
            log.error("Cannot read InputStream from the file " + logFile, e);
            throw e;
        } catch (IOException e) {
            String msg = "Cannot read file size from the " + logFile;
            log.error(msg, e);
            throw new LogViewerException(msg, e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("Error while closing inputStream of log file", e);
                }
            }
        }
    }

    private boolean isSyslogOn() {
        SyslogConfiguration syslogConfig = SyslogConfigManager.loadSyslogConfiguration();
        return syslogConfig.isSyslogOn();
    }


    private List<LogFileInfo> getSortedPerLogInfoList(List<LogFileInfo> logs) {
        if (logs == null || logs.isEmpty()) {
            return getDefaultLogInfoList();
        } else {
            Collections.sort(logs, new Comparator<Object>() {
                public int compare(Object o1, Object o2) {
                    LogFileInfo log1 = (LogFileInfo) o1;
                    LogFileInfo log2 = (LogFileInfo) o2;
                    return log1.getLogName().compareToIgnoreCase(log2.getLogName());
                }

            });
            return logs;
        }
    }

    private InputStream getLogDataStream(String logFile, int tenantId, String productName)
            throws Exception {
        SyslogData syslogData = getSyslogData();    //throws an Exception, so cannot throw a
                                                    // specific exception from getLogDataStream()
        String url;
        // manager can view all the products tenant log information
        url = getLogsServerURLforTenantService(syslogData.getUrl(), logFile, tenantId, productName);
        String password = <PASSWORD>();
        String userName = syslogData.getUserName();
        int port = Integer.parseInt(syslogData.getPort());
        String realm = syslogData.getRealm();
        URI uri = new URI(url);
        String host = uri.getHost();
        HttpClient client = new HttpClient();
        client.getState().setCredentials(new AuthScope(host, port, realm),
                new UsernamePasswordCredentials(userName, password));
        GetMethod get = new GetMethod(url);
        get.setDoAuthentication(true);
        client.executeMethod(get);
        return get.getResponseBodyAsStream();
    }

    private SyslogData getSyslogData() throws Exception {
        return LoggingUtil.getSyslogData();
    }

    private String getLogsServerURLforTenantService(String syslogServerURL, String logFile,
                                                    int tenantId, String serverKey) throws LogViewerException {
        String serverUrl;
        String lastChar = String.valueOf(syslogServerURL.charAt(syslogServerURL.length() - 1));
        if (lastChar.equals(LoggingConstants.URL_SEPARATOR)) { // http://my.log.server/logs/stratos/
            syslogServerURL = syslogServerURL.substring(0, syslogServerURL.length() - 1);
        }
        if (isSuperTenantUser()) {
            // ST can view tenant specific log files.
            if (isManager()) {
                // manager can view different services log
                // messages.
                if (serverKey != null && serverKey.length() > 0) {
                    serverUrl = getServerUrl(syslogServerURL, tenantId, serverKey);
                } else {
                    serverUrl = getServerUrl(syslogServerURL, tenantId,
                                             LoggingConstants.WSO2_STRATOS_MANAGER);
                }
                if (!isStratosService()) {
                    // stand-alone apps.
                    serverUrl = getServerUrl(syslogServerURL, tenantId,
                                             ServerConfiguration.getInstance()
                                                                .getFirstProperty(SERVER_KEY));
                }
            } else {
                // for other stratos services can view only their relevant
                // logs.
                serverUrl = getServerUrl(syslogServerURL, tenantId,
                                         ServerConfiguration.getInstance()
                                                            .getFirstProperty(SERVER_KEY));
            }

        } else {
            // tenant level logging
            if (isManager()) {
                if (serverKey != null && serverKey.length() > 0) {
                    serverUrl = getServerUrl(syslogServerURL,
                                             CarbonContext.getThreadLocalCarbonContext()
                                                          .getTenantId(),
                                             serverKey);
                } else {
                    serverUrl = getServerUrl(syslogServerURL,
                                             CarbonContext.getThreadLocalCarbonContext()
                                                          .getTenantId(),
                                             LoggingConstants.WSO2_STRATOS_MANAGER);
                }
            } else {
                serverUrl = getServerUrl(syslogServerURL,
                                         CarbonContext.getThreadLocalCarbonContext().getTenantId(),
                                         ServerConfiguration.getInstance()
                                                            .getFirstProperty(SERVER_KEY));
            }
        }
        serverUrl = serverUrl.replaceAll("\\s", URL_ENCODED_SPACE_CHAR);
        logFile = logFile.replaceAll("\\s", URL_ENCODED_SPACE_CHAR);
        return serverUrl + logFile;
    }

    private String getServerUrl(String syslogServerURL, int tenantId, String serverKey) {
        return syslogServerURL + LoggingConstants.URL_SEPARATOR + tenantId
                + LoggingConstants.URL_SEPARATOR + serverKey + LoggingConstants.URL_SEPARATOR;
    }

    private boolean isStratosService() throws LogViewerException {
        String serverKey = ServerConfiguration.getInstance().getFirstProperty(SERVER_KEY);
        return ServiceConfigManager.isStratosService(serverKey);
    }

    private boolean isManager() {
        return LoggingConstants.WSO2_STRATOS_MANAGER.equalsIgnoreCase(ServerConfiguration.getInstance()
                .getFirstProperty(SERVER_KEY));
    }

    private boolean isSuperTenantUser() {
        CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
        int tenantId = carbonContext.getTenantId();
        return tenantId == MultitenantConstants.SUPER_TENANT_ID;
    }

    private String getCurrentServerName() {
        return ServerConfiguration.getInstance().getFirstProperty(SERVER_KEY);
    }

    private String getFileSize(File file) {
        long bytes = file.length();
        int unit = 1024;
        if (bytes < unit) {
            return bytes + " B";
        }
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        char pre = "KMGTPE".charAt(exp - 1);
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }

    private InputStream getInputStream(String logFile, int tenantId, String serverKey)
            throws LogViewerException {
        InputStream inputStream;
        try {
            if (isSyslogOn()) {
                inputStream = getLogDataStream(logFile, tenantId, serverKey);
            } else {
                if (isSuperTenantUser()) {
                    Path logFilePath = Paths.get(CarbonUtils.getCarbonLogsPath(), logFile);
                    if (!isPathInsideBaseDirectory(Paths.get(CarbonUtils.getCarbonLogsPath()), logFilePath)) {
                        throw new LogViewerException("Specified log file path is outside carbon logs directory.");
                    }
                    FileAppender carbonLogFileAppender =
                            (FileAppender) Logger.getRootLogger().getAppender(CARBON_LOGFILE_APPENDER);
                    String carbonLogFileName = new File(carbonLogFileAppender.getFile()).getName();

                    if (!logFilePath.getFileName().toString().startsWith(carbonLogFileName)) {
                        throw new LogViewerException("Trying to access logs other than " +
                                "CARBON_LOGFILE appender log file.");
                    }
                    inputStream = getLocalInputStream(logFilePath.toString());
                } else {
                    throw new LogViewerException("Syslog Properties are not properly configured");
                }
            }
            return inputStream;
        } catch (Exception e) {
            // cannot catch a specific exception since RegistryManager.getSyslogConfig (which is
            // used in the call stack of getLogDataStream()) throws an exception 
            throw new LogViewerException("Error getting the file input stream", e);
        }
    }

    private InputStream getLocalInputStream(String logFile) throws FileNotFoundException {
        return new BufferedInputStream(new FileInputStream(logFile));
    }


    private List<LogFileInfo> getDefaultLogInfoList() {
        List<LogFileInfo> defaultLogFileInfoList = new ArrayList<LogFileInfo>();
        defaultLogFileInfoList.add(new LogFileInfo("NO_LOG_FILES",
                                           "---", "---"));
        return defaultLogFileInfoList;
    }

    /**
     * Tests if the provided path is inside the base directory path.
     *
     * @param baseDirPath absolute {@link Path} of the base directory in which we want to check whether the given path
     *                    is inside
     * @param path        relative {@link Path} to be tested
     * @return {@code true} if the given path is inside the base directory path, otherwise {@code false}
     */
    private static boolean isPathInsideBaseDirectory(Path baseDirPath, Path path) {
        Path resolvedPath = baseDirPath.resolve(path.normalize()).normalize();
        return resolvedPath.startsWith(baseDirPath.normalize());
    }
}
