Example usage for org.apache.commons.logging Log debug

List of usage examples for org.apache.commons.logging Log debug

Introduction

In this page you can find the example usage for org.apache.commons.logging Log debug.

Prototype

void debug(Object message);

Source Link

Document

Logs a message with debug log level.

Usage

From source file:org.expath.httpclient.impl.LoggerHelper.java

public static void logCookies(Log log, String prompt, Iterable<Cookie> cookies) {
    if (log.isDebugEnabled()) {
        if (cookies == null) {
            log.debug(prompt + ": null");
            return;
        }/*from  w w w  . j a v  a2s  .c o m*/
        for (Cookie c : cookies) {
            log.debug(prompt + ": " + c.getName() + ": " + c.getValue());
        }
    }
}

From source file:org.expath.httpclient.impl.LoggerHelper.java

public static void logHeaders(Log log, String prompt, Header[] headers) {
    if (log.isDebugEnabled()) {
        if (headers == null) {
            log.debug(prompt + ": null");
            return;
        }//from  www .  j  a va2 s. c  o m
        for (Header h : headers) {
            log.debug(prompt + ": " + h.getName() + ": " + h.getValue());
        }
    }
}

From source file:org.expath.httpclient.impl.LoggerHelper.java

public static void logHeaderDetails(Log log, String prompt, Iterable<Header> headers) {
    if (log.isDebugEnabled()) {
        if (headers == null) {
            log.debug(prompt + ": null");
            return;
        }//from w  w  w  . j a  v  a  2  s.  c  o  m
        for (Header h : headers) {
            log.debug(prompt + " - HEADER: " + h.getName() + ": " + h.getValue());
            for (HeaderElement e : h.getElements()) {
                log.debug(prompt + " -   ELEM: " + e.getName() + ": " + e.getValue());
                for (NameValuePair p : e.getParameters()) {
                    log.debug(prompt + " -     P: " + p.getName() + ": " + p.getValue());
                }
            }
        }
    }
}

From source file:org.gcaldaemon.core.Configurator.java

public Configurator(String configPath, Properties properties, boolean userHome, byte mode) throws Exception {
    this.mode = mode;
    int i;//ww w  . jav  a 2s  .  c o  m
    File programRootDir = null;
    if (mode == MODE_EMBEDDED) {

        // Embedded mode
        standaloneMode = false;
        config = properties;
        String workPath = getConfigProperty(WORK_DIR, null);
        workDirectory = new File(workPath);
    } else {

        // Load config
        if (configPath != null) {
            configFile = new File(configPath);
        }
        InputStream in = null;
        boolean configInClassPath = false;
        if (configFile == null || !configFile.isFile()) {
            try {
                in = Configurator.class.getResourceAsStream("/gcal-daemon.cfg");
                configInClassPath = in != null;
            } catch (Exception ignored) {
                in = null;
            }
            if (in == null) {
                System.out.println("INFO  | Searching main configuration file...");
                String path = (new File("x")).getAbsolutePath().replace('\\', '/');
                i = path.lastIndexOf('/');
                if (i > 1) {
                    i = path.lastIndexOf('/', i - 1);
                    if (i > 1) {
                        configFile = new File(path.substring(0, i), "conf/gcal-daemon.cfg");
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/usr/local/sbin/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    File root = new File("/");
                    String[] dirs = root.list();
                    if (dirs != null) {
                        for (i = 0; i < dirs.length; i++) {
                            configFile = new File('/' + dirs[i] + "/GCALDaemon/conf/gcal-daemon.cfg");
                            if (configFile.isFile()) {
                                break;
                            }
                        }
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    throw new FileNotFoundException("Missing main configuration file: " + configPath);
                }
                if (!userHome) {

                    // Open global config file
                    in = new FileInputStream(configFile);
                }
            }
        } else {
            if (!userHome) {

                // Open global config file
                in = new FileInputStream(configFile);
            }
        }
        standaloneMode = !configInClassPath;
        if (in != null) {

            // Load global config file
            config.load(new BufferedInputStream(in));
            in.close();
        }

        // Loading config from classpath
        if (configFile == null) {
            try {
                URL url = Configurator.class.getResource("/gcal-daemon.cfg");
                configFile = new File(url.getFile());
            } catch (Exception ignored) {
            }
        }
        programRootDir = configFile.getParentFile().getParentFile();
        System.setProperty("gcaldaemon.program.dir", programRootDir.getAbsolutePath());
        String workPath = getConfigProperty(WORK_DIR, null);
        File directory;
        if (workPath == null) {
            directory = new File(programRootDir, "work");
        } else {
            directory = new File(workPath);
        }
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                directory = new File("work");
                directory.mkdirs();
            }
        }
        workDirectory = directory;

        // User-specific config file handler
        if (userHome) {
            boolean useGlobal = true;
            try {
                String home = System.getProperty("user.home", null);
                if (home != null) {
                    File userConfig = new File(home, ".gcaldaemon/gcal-daemon.cfg");
                    if (!userConfig.isFile()) {

                        // Create new user-specific config
                        File userDir = new File(home, ".gcaldaemon");
                        userDir.mkdirs();
                        copyFile(configFile, userConfig);
                        if (!userConfig.isFile()) {
                            userConfig.delete();
                            userDir.delete();
                        }
                    }
                    if (userConfig.isFile()) {

                        // Load user-specific config
                        configFile = userConfig;
                        in = new FileInputStream(configFile);
                        config.load(new BufferedInputStream(in));
                        in.close();
                        useGlobal = false;
                    }
                }
            } catch (Exception ignored) {
            }
            if (useGlobal) {

                // Load global config file
                config.load(new BufferedInputStream(in));
                in.close();
            }
        }
    }

    // Init logger
    ProgressMonitor monitor = null;
    if (standaloneMode && mode != MODE_CONFIGEDITOR) {

        // Compute log config path
        String logConfig = getConfigProperty(LOG_CONFIG, "logger-config.cfg");
        logConfig = logConfig.replace('\\', '/');
        File logConfigFile;
        if (logConfig.indexOf('/') == -1) {
            logConfigFile = new File(programRootDir, "conf/" + logConfig);
        } else {
            logConfigFile = new File(logConfig);
        }
        if (logConfigFile.isFile()) {
            String logConfigPath = logConfigFile.getAbsolutePath();
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
            System.setProperty("log4j.defaultInitOverride", "false");
            System.setProperty("log4j.configuration", logConfigPath);
            try {
                PropertyConfigurator.configure(logConfigPath);
            } catch (Throwable ignored) {
            }
        }
    }
    if (mode == MODE_CONFIGEDITOR) {

        // Show monitor
        try {
            monitor = new ProgressMonitor();
            monitor.setVisible(true);
            Thread.sleep(400);
        } catch (Exception ignored) {
        }

        // Init simple logger
        try {
            System.setProperty("log4j.defaultInitOverride", "false");
            Logger root = Logger.getRootLogger();
            root.removeAllAppenders();
            root.addAppender(new ConsoleAppender(new SimpleLayout()));
            root.setLevel(Level.INFO);
        } catch (Throwable ingored) {
        }
    }

    // Disable unnecessary INFO messages of the GData API
    try {
        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.google");
        logger.setLevel(java.util.logging.Level.WARNING);
    } catch (Throwable ingored) {
    }

    Log log = LogFactory.getLog(Configurator.class);
    log.info(VERSION + " starting...");
    if (configFile != null && log.isDebugEnabled()) {
        log.debug("Config loaded successfully (" + configFile + ").");
    }

    // Check Java version
    double jvmVersion = 1.5;
    try {
        jvmVersion = Float.valueOf(System.getProperty("java.version", "1.5").substring(0, 3)).floatValue();
    } catch (Exception ignored) {
    }
    if (jvmVersion < 1.5) {
        log.fatal("GCALDaemon requires at least Java 1.5! Current version: "
                + System.getProperty("java.version"));
        throw new Exception("Invalid JVM version!");
    }

    // Check permission
    if (workDirectory.isDirectory() && !workDirectory.canWrite()) {
        if (System.getProperty("os.name", "unknown").toLowerCase().indexOf("windows") == -1) {
            String path = workDirectory.getCanonicalPath();
            if (programRootDir != null) {
                path = programRootDir.getCanonicalPath();
            }
            log.warn("Please check the file permissions on the '" + workDirectory.getCanonicalPath()
                    + "' folder!\r\n" + "Hint: [sudo] chmod -R 777 " + path);
        }
    }

    // Disable all ICS file syntax validators
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_NOTES_COMPATIBILITY, true);

    // Disable SSL validation
    try {

        // Create a trust manager that does not validate certificate chains
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] {
                new javax.net.ssl.X509TrustManager() {

                    public final java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public final void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }

                    public final void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }
                } };

        // Install the all-trusting trust manager
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Throwable ignored) {
    }

    // Replace hostname verifier
    try {
        javax.net.ssl.HostnameVerifier hv[] = new javax.net.ssl.HostnameVerifier[] {
                new javax.net.ssl.HostnameVerifier() {

                    public final boolean verify(String hostName, javax.net.ssl.SSLSession session) {
                        return true;
                    }
                } };
        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv[0]);
    } catch (Throwable ignored) {
    }

    // Setup proxy
    String proxyHost = getConfigProperty(PROXY_HOST, null);
    if (proxyHost != null) {
        String proxyPort = getConfigProperty(PROXY_PORT, null);
        if (proxyPort == null) {
            log.warn("Missing 'proxy.port' configuration property!");
        } else {

            // HTTP proxy server properties
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            System.setProperty("http.proxySet", "true");

            // HTTPS proxy server properties
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            System.setProperty("https.proxySet", "true");

            // Setup proxy credentials
            String username = getConfigProperty(PROXY_USERNAME, null);
            String encodedPassword = getConfigProperty(PROXY_PASSWORD, null);
            if (username != null) {
                if (encodedPassword == null) {
                    log.warn("Missing 'proxy.password' configuration property!");
                } else {
                    String password = StringUtils.decodePassword(encodedPassword);

                    // HTTP auth credentials
                    System.setProperty("http.proxyUser", username);
                    System.setProperty("http.proxyUserName", username);
                    System.setProperty("http.proxyPassword", password);

                    // HTTPS auth credentials
                    System.setProperty("https.proxyUser", username);
                    System.setProperty("https.proxyUserName", username);
                    System.setProperty("https.proxyPassword", password);
                }
            }
        }
    }

    // Get iCal cache timeout
    long timeout = getConfigProperty(CACHE_TIMEOUT, 180000L);
    if (timeout < 60000L) {
        log.warn("The enabled minimal cache timeout is '1 min'!");
        timeout = 60000L;
    }
    calendarCacheTimeout = timeout;

    // Get backup file timeout
    timeout = getConfigProperty(ICAL_BACKUP_TIMEOUT, 604800000L);
    if (timeout < 86400000L && timeout != 0) {
        log.warn("The enabled minimal backup timeout is '1 day'!");
        timeout = 86400000L;
    }
    backupTimeout = timeout;

    // Get extended syncronization mode (alarms, url, category, etc)
    boolean enable = getConfigProperty(EXTENDED_SYNC_ENABLED, false);
    System.setProperty("gcaldaemon.extended.sync", Boolean.toString(enable));
    if (enable) {
        log.info("Extended synchronization enabled.");
    }

    // Google send an email to the attendees to invite them to attend
    enable = getConfigProperty(SEND_INVITATIONS, false);
    System.setProperty("gcaldaemon.send.invitations", Boolean.toString(enable));

    // Enabled alarm types in the Google Calendar (e.g. 'sms,popup,email')
    System.setProperty("gcaldaemon.remote.alarms", getConfigProperty(REMOTE_ALARM_TYPES, "email,sms,popup"));

    // Get parameters of the feed to iCal converter
    feedEnabled = getConfigProperty(FEED_ENABLED, true);
    feedEventLength = getConfigProperty(FEED_EVENT_LENGTH, 2700000L);
    timeout = getConfigProperty(FEED_CACHE_TIMEOUT, 3600000L);
    if (timeout < 60000L) {
        log.warn("The enabled minimal feed timeout is '1 min'!");
        timeout = 60000L;
    }
    feedCacheTimeout = timeout;
    if (feedEnabled) {
        log.info("RSS/ATOM feed converter enabled.");
    } else {
        log.info("RSS/ATOM feed converter disabled.");
    }

    // Get feed event duplication ratio
    String percent = getConfigProperty(FEED_DUPLICATION_FILTER, "70").trim();
    if (percent.endsWith("%")) {
        percent = percent.substring(0, percent.length() - 1).trim();
    }
    double ratio = Double.parseDouble(percent) / 100;
    if (ratio < 0.4) {
        ratio = 0.4;
        log.warn("The smallest enabled filter percent is '40%'!");
    } else {
        if (ratio > 1) {
            log.warn("The largest filter percent is '100%'!");
            ratio = 1;
        }
    }
    duplicationRatio = ratio;
    if (feedEnabled) {
        if (duplicationRatio == 1) {
            log.debug("Duplication filter disabled.");
        } else {
            log.debug("Sensibility of the duplication filter is " + percent + "%.");
        }
    }

    // Delete backup files
    if (backupTimeout == 0) {
        File backupDirectory = new File(workDirectory, "backup");
        if (backupDirectory.isDirectory()) {
            File[] backups = backupDirectory.listFiles();
            if (backups != null && backups.length != 0) {
                for (i = 0; i < backups.length; i++) {
                    backups[i].delete();
                }
            }
        }
    }

    // Displays time zone
    log.info("Local time zone is " + TimeZone.getDefault().getDisplayName() + ".");

    // Get main thread group
    ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
    while (mainGroup.getParent() != null) {
        mainGroup = mainGroup.getParent();
    }

    // Configurator mode - launch ConfigTool's window
    if (mode == MODE_CONFIGEDITOR) {
        synchronizer = new Synchronizer(mainGroup, this);
        gmailPool = startService(log, mainGroup, "org.gcaldaemon.core.GmailPool");
        new ConfigEditor(this, monitor);
        return;
    }

    // Init synchronizer
    boolean enableHTTP = getConfigProperty(HTTP_ENABLED, true);
    boolean enableFile = getConfigProperty(FILE_ENABLED, false);
    if (enableHTTP || enableFile || !standaloneMode) {
        synchronizer = new Synchronizer(mainGroup, this);
        if (mode == MODE_EMBEDDED) {
            return;
        }
    }

    // On demand mode - run once then quit
    if (mode == MODE_RUNONCE) {
        fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OfflineFileListener");
        return;
    }

    // Init Gmail pool
    boolean enableLDAP = getConfigProperty(LDAP_ENABLED, false);
    boolean enableSendMail = getConfigProperty(SENDMAIL_ENABLED, false);
    boolean enableMailTerm = getConfigProperty(MAILTERM_ENABLED, false);
    if (enableLDAP || enableSendMail || enableMailTerm) {
        gmailPool = startService(log, mainGroup, "org.gcaldaemon.core.GmailPool");
    }

    if (standaloneMode) {

        // Init HTTP listener
        if (enableHTTP) {
            httpListener = startService(log, mainGroup, "org.gcaldaemon.core.http.HTTPListener");
        } else {
            log.info("HTTP server disabled.");
        }
    } else {

        // Init J2EE servlet listener
        servletListener = startService(log, mainGroup, "org.gcaldaemon.core.servlet.ServletListener");
    }

    // Init file listener
    if (enableFile) {
        if (getConfigProperty(FILE_OFFLINE_ENABLED, true)) {
            fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OfflineFileListener");
        } else {
            fileListener = startService(log, mainGroup, "org.gcaldaemon.core.file.OnlineFileListener");
        }
    } else {
        if (standaloneMode) {
            log.info("File listener disabled.");
        }
    }

    // Init LDAP listener
    if (enableLDAP) {
        contactLoader = startService(log, mainGroup, "org.gcaldaemon.core.ldap.ContactLoader");
    } else {
        if (standaloneMode) {
            log.info("LDAP server disabled.");
        }
    }

    // Init Gmail notifier
    if (getConfigProperty(NOTIFIER_ENABLED, false)) {
        if (GraphicsEnvironment.isHeadless()) {
            log.warn("Unable to use Gmail notifier in headless mode!");
        } else {
            mailNotifier = startService(log, mainGroup, "org.gcaldaemon.core.notifier.GmailNotifier");
        }
    } else {
        if (standaloneMode) {
            log.info("Gmail notifier disabled.");
        }
    }

    // Init sendmail service
    if (enableSendMail) {
        sendMail = startService(log, mainGroup, "org.gcaldaemon.core.sendmail.SendMail");
    } else {
        if (standaloneMode) {
            log.info("Sendmail service disabled.");
        }
    }

    // Init mailterm service
    if (enableMailTerm) {
        mailTerm = startService(log, mainGroup, "org.gcaldaemon.core.mailterm.MailTerminal");
    } else {
        if (standaloneMode) {
            log.info("Mail terminal disabled.");
        }
    }

    // Clear configuration holder
    config.clear();
}

From source file:org.gldapdaemon.core.Configurator.java

public Configurator(String configPath, Properties properties, boolean userHome, byte mode) throws Exception {
    this.mode = mode;
    int i;/*from   w  w  w  .ja  v  a 2 s. c  o m*/
    File programRootDir = null;
    if (mode == MODE_EMBEDDED) {

        // Embedded mode
        standaloneMode = false;
        config = properties;
        String workPath = getConfigProperty(WORK_DIR, null);
        workDirectory = new File(workPath);
    } else {

        // Load config
        if (configPath != null) {
            configFile = new File(configPath);
        }
        InputStream in = null;
        boolean configInClassPath = false;
        if (configFile == null || !configFile.isFile()) {
            try {
                in = Configurator.class.getResourceAsStream("/gcal-daemon.cfg");
                configInClassPath = in != null;
            } catch (Exception ignored) {
                in = null;
            }
            if (in == null) {
                System.out.println("INFO  | Searching main configuration file...");
                String path = (new File("x")).getAbsolutePath().replace('\\', '/');
                i = path.lastIndexOf('/');
                if (i > 1) {
                    i = path.lastIndexOf('/', i - 1);
                    if (i > 1) {
                        configFile = new File(path.substring(0, i), "conf/gcal-daemon.cfg");
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/usr/local/sbin/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    configFile = new File("/GCALDaemon/conf/gcal-daemon.cfg");
                }
                if (configFile == null || !configFile.isFile()) {
                    File root = new File("/");
                    String[] dirs = root.list();
                    if (dirs != null) {
                        for (i = 0; i < dirs.length; i++) {
                            configFile = new File('/' + dirs[i] + "/GCALDaemon/conf/gcal-daemon.cfg");
                            if (configFile.isFile()) {
                                break;
                            }
                        }
                    }
                }
                if (configFile == null || !configFile.isFile()) {
                    throw new FileNotFoundException("Missing main configuration file: " + configPath);
                }
                if (!userHome) {

                    // Open global config file
                    in = new FileInputStream(configFile);
                }
            }
        } else {
            if (!userHome) {
                // Open global config file
                in = new FileInputStream(configFile);
            }
        }
        standaloneMode = !configInClassPath;
        if (in != null) {

            // Load global config file
            config.load(new BufferedInputStream(in));
            in.close();
        }

        // Loading config from classpath
        if (configFile == null) {
            try {
                URL url = Configurator.class.getResource("/gcal-daemon.cfg");
                configFile = new File(url.getFile());
            } catch (Exception ignored) {
            }
        }
        programRootDir = configFile.getParentFile().getParentFile();
        System.setProperty("gldapdaemon.program.dir", programRootDir.getAbsolutePath());
        String workPath = getConfigProperty(WORK_DIR, null);
        File directory;
        if (workPath == null) {
            directory = new File(programRootDir, "work");
        } else {
            directory = new File(workPath);
        }
        if (!directory.isDirectory()) {
            if (!directory.mkdirs()) {
                directory = new File("work");
                directory.mkdirs();
            }
        }
        workDirectory = directory;

        // User-specific config file handler
        if (userHome) {
            boolean useGlobal = true;
            try {
                String home = System.getProperty("user.home", null);
                if (home != null) {
                    File userConfig = new File(home, ".gcaldaemon/gcal-daemon.cfg");
                    if (!userConfig.isFile()) {

                        // Create new user-specific config
                        File userDir = new File(home, ".gcaldaemon");
                        userDir.mkdirs();
                        copyFile(configFile, userConfig);
                        if (!userConfig.isFile()) {
                            userConfig.delete();
                            userDir.delete();
                        }
                    }
                    if (userConfig.isFile()) {

                        // Load user-specific config
                        configFile = userConfig;
                        in = new FileInputStream(configFile);
                        config.load(new BufferedInputStream(in));
                        in.close();
                        useGlobal = false;
                    }
                }
            } catch (Exception ignored) {
            }
            if (useGlobal) {

                // Load global config file
                config.load(new BufferedInputStream(in));
                in.close();
            }
        }
    }

    // Init logger
    ProgressMonitor monitor = null;
    if (standaloneMode && mode != MODE_CONFIGEDITOR) {

        // Compute log config path
        String logConfig = getConfigProperty(LOG_CONFIG, "logger-config.cfg");
        logConfig = logConfig.replace('\\', '/');
        File logConfigFile;
        if (logConfig.indexOf('/') == -1) {
            logConfigFile = new File(programRootDir, "conf/" + logConfig);
        } else {
            logConfigFile = new File(logConfig);
        }
        if (logConfigFile.isFile()) {
            String logConfigPath = logConfigFile.getAbsolutePath();
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");
            System.setProperty("log4j.defaultInitOverride", "false");
            System.setProperty("log4j.configuration", logConfigPath);
            try {
                PropertyConfigurator.configure(logConfigPath);
            } catch (Throwable ignored) {
                ignored.printStackTrace();
            }
        }
    }
    if (mode == MODE_CONFIGEDITOR) {

        // Show monitor
        try {
            monitor = new ProgressMonitor();
            monitor.setVisible(true);
            Thread.sleep(400);
        } catch (Exception ignored) {
        }

        // Init simple logger
        try {
            System.setProperty("log4j.defaultInitOverride", "false");
            Logger root = Logger.getRootLogger();
            root.removeAllAppenders();
            root.addAppender(new ConsoleAppender(new SimpleLayout()));
            root.setLevel(Level.INFO);
        } catch (Throwable ingored) {
        }
    }

    // Disable unnecessary INFO messages of the GData API
    try {
        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("com.google");
        logger.setLevel(java.util.logging.Level.WARNING);
    } catch (Throwable ingored) {
    }

    Log log = LogFactory.getLog(Configurator.class);
    log.info(VERSION + " starting...");
    if (configFile != null && log.isDebugEnabled()) {
        log.debug("Config loaded successfully (" + configFile + ").");
    }

    // Check Java version
    double jvmVersion = 1.5;
    try {
        jvmVersion = Float.valueOf(System.getProperty("java.version", "1.5").substring(0, 3)).floatValue();
    } catch (Exception ignored) {
    }
    if (jvmVersion < 1.5) {
        log.fatal("GCALDaemon requires at least Java 1.5! Current version: "
                + System.getProperty("java.version"));
        throw new Exception("Invalid JVM version!");
    }

    // Check permission
    if (workDirectory.isDirectory() && !workDirectory.canWrite()) {
        if (System.getProperty("os.name", "unknown").toLowerCase().indexOf("windows") == -1) {
            String path = workDirectory.getCanonicalPath();
            if (programRootDir != null) {
                path = programRootDir.getCanonicalPath();
            }
            log.warn("Please check the file permissions on the '" + workDirectory.getCanonicalPath()
                    + "' folder!\r\n" + "Hint: [sudo] chmod -R 777 " + path);
        }
    }

    // Disable SSL validation
    try {
        // Create a trust manager that does not validate certificate chains
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[] {
                new javax.net.ssl.X509TrustManager() {

                    public final java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public final void checkClientTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }

                    public final void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                            String authType) {
                    }
                } };

        // Install the all-trusting trust manager
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Throwable ignored) {
    }

    // Replace hostname verifier
    try {
        javax.net.ssl.HostnameVerifier hv[] = new javax.net.ssl.HostnameVerifier[] {
                new javax.net.ssl.HostnameVerifier() {

                    public final boolean verify(String hostName, javax.net.ssl.SSLSession session) {
                        return true;
                    }
                } };

        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv[0]);
    } catch (Throwable ignored) {
    }

    // Setup proxy
    String proxyHost = getConfigProperty(PROXY_HOST, null);
    if (proxyHost != null) {
        String proxyPort = getConfigProperty(PROXY_PORT, null);
        if (proxyPort == null) {
            log.warn("Missing 'proxy.port' configuration property!");
        } else {

            // HTTP proxy server properties
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            System.setProperty("http.proxySet", "true");

            // HTTPS proxy server properties
            System.setProperty("https.proxyHost", proxyHost);
            System.setProperty("https.proxyPort", proxyPort);
            System.setProperty("https.proxySet", "true");

            // Setup proxy credentials
            String username = getConfigProperty(PROXY_USERNAME, null);
            String encodedPassword = getConfigProperty(PROXY_PASSWORD, null);
            if (username != null) {
                if (encodedPassword == null) {
                    log.warn("Missing 'proxy.password' configuration property!");
                } else {
                    String password = StringUtils.decodePassword(encodedPassword);

                    // HTTP auth credentials
                    System.setProperty("http.proxyUser", username);
                    System.setProperty("http.proxyUserName", username);
                    System.setProperty("http.proxyPassword", password);

                    // HTTPS auth credentials
                    System.setProperty("https.proxyUser", username);
                    System.setProperty("https.proxyUserName", username);
                    System.setProperty("https.proxyPassword", password);
                }
            }
        }
    }

    // Get feed event duplication ratio
    String percent = getConfigProperty(FEED_DUPLICATION_FILTER, "70").trim();
    if (percent.endsWith("%")) {
        percent = percent.substring(0, percent.length() - 1).trim();
    }
    double ratio = Double.parseDouble(percent) / 100;
    if (ratio < 0.4) {
        ratio = 0.4;
        log.warn("The smallest enabled filter percent is '40%'!");
    } else {
        if (ratio > 1) {
            log.warn("The largest filter percent is '100%'!");
            ratio = 1;
        }
    }
    duplicationRatio = ratio;

    // Displays time zone
    log.info("Local time zone is " + TimeZone.getDefault().getDisplayName() + ".");

    // Get main thread group
    ThreadGroup mainGroup = Thread.currentThread().getThreadGroup();
    while (mainGroup.getParent() != null) {
        mainGroup = mainGroup.getParent();
    }

    // Init Gmail pool
    boolean enableLDAP = getConfigProperty(LDAP_ENABLED, false);
    if (enableLDAP) {
        gmailPool = startService(log, mainGroup, "org.gldapdaemon.core.GmailPool");
    }

    // Init LDAP listener
    if (enableLDAP) {
        contactLoader = startService(log, mainGroup, "org.gldapdaemon.core.ldap.ContactLoader");
    } else {
        if (standaloneMode) {
            log.info("LDAP server disabled.");
        }
    }

    // Clear configuration holder
    config.clear();
}

From source file:org.holodeckb2b.common.workerpool.xml.XMLWorkerPoolConfig.java

/**
 * Loads the worker pool configuration from file. 
 * /*from  ww  w  . j  a  va2 s.  com*/
 * @param path      Path to the XML document containing the pool's configuration
 * @return          The worker pool configuration if succesfully loaded, null otherwise
 */
public static IWorkerPoolConfiguration loadFromFile(String path) {
    Log log = LogFactory.getLog(XMLWorkerPoolConfig.class);
    XMLWorkerPoolConfig poolCfg = null;

    log.debug("Loading worker pool configuration from XML document in " + path);

    File f = new File(path);

    if (f.exists() && f.canRead()) {
        Serializer serializer = new Persister();
        try {
            poolCfg = serializer.read(XMLWorkerPoolConfig.class, f);
            // If config file does not set pool name, set it here to file name
            if (poolCfg.getName() == null || poolCfg.getName().isEmpty())
                poolCfg.name = f.getName().substring(0, f.getName().indexOf("."));
            log.debug("Loaded configuration");
        } catch (Exception ex) {
            log.error("Error while reading configuration from " + path + "! Details: " + ex.getMessage());
        }
    } else
        log.error("Unable to access configuration file" + path + "!");

    return poolCfg;
}

From source file:org.holodeckb2b.ebms.axis2.Axis2Sender.java

/**
 * Send the message unit to the other MSH. 
 * /*w  ww .j a va2  s  .c om*/
 * @param message   The MessageUnit to send 
 * @param log       The log to use for writing log information
 */
public static void sendMessage(EntityProxy msgProxy, Log log) {
    ServiceClient sc;
    OperationClient oc;
    MessageContext msgCtx = new MessageContext();

    MessageUnit message = msgProxy.entity;
    try {
        log.debug("Prepare Axis2 client to send " + message.getClass().getSimpleName());
        sc = new ServiceClient(HolodeckB2BCoreInterface.getConfiguration().getAxisConfigurationContext(),
                Axis2Utils.createAnonymousService());
        sc.engageModule(HolodeckB2BCoreImpl.HOLODECKB2B_CORE_MODULE);
        oc = sc.createClient(ANON_OUT_IN_OP);

        log.debug("Create an empty MessageContext for message with current configuration");

        if (message instanceof UserMessage) {
            log.debug("Message to send is a UserMessage");
            msgCtx.setProperty(MessageContextProperties.OUT_USER_MESSAGE, msgProxy);
        } else if (message instanceof PullRequest) {
            log.debug("Message to send is a PullRequest");
            msgCtx.setProperty(MessageContextProperties.OUT_PULL_REQUEST, msgProxy);
        } else if (message instanceof ErrorMessage) {
            log.debug("Message to send is a ErrorMessage");
            MessageContextUtils.addErrorSignalToSend(msgCtx, msgProxy);
        } else if (message instanceof Receipt) {
            log.debug("Message to send is a Receipt");
            MessageContextUtils.addReceiptToSend(msgCtx, msgProxy);
        }
        oc.addMessageContext(msgCtx);

        // This dummy EPR has to be provided to be able to trigger message sending. It will be replaced later
        // with the correct URL defined in the P-Mode
        EndpointReference targetEPR = new EndpointReference("http://holodeck-b2b.org/transport/dummy");
        Options options = new Options();
        options.setTo(targetEPR);
        options.setExceptionToBeThrownOnSOAPFault(false);
        oc.setOptions(options);

        log.debug("Axis2 client configured for sending ebMS message");
    } catch (AxisFault af) {
        // Setting up the Axis environment failed. As it prevents sending the message it is logged as a fatal error 
        log.fatal("Setting up Axis2 to send message failed! Details: " + af.getReason());
        return;
    }

    try {
        log.debug("Start the message send process");
        oc.execute(true);
    } catch (AxisFault af) {
        /* An error occurred while sending the message, it should however be already processed by one of the 
           handlers. In that case the message context will not contain the failure reason. To prevent redundant 
           logging we check if there is a failure reason before we log the error here.
        */
        List<Throwable> errorStack = Utils.getCauses(af);
        StringBuilder logMsg = new StringBuilder("\n\tError stack: ")
                .append(errorStack.get(0).getClass().getSimpleName());
        for (int i = 1; i < errorStack.size(); i++) {
            logMsg.append("\n\t    Caused by: ").append(errorStack.get(i).getClass().getSimpleName());
        }
        logMsg.append(" {").append(errorStack.get(errorStack.size() - 1).getMessage()).append('}');
        log.error("An error occurred while sending the message [" + message.getMessageId() + "]!"
                + logMsg.toString());
    } finally {
        try {
            sc.cleanupTransport();
            sc.cleanup();
        } catch (AxisFault af2) {
            log.error("Clean up of Axis2 context to send message failed! Details: " + af2.getReason());
        }
    }
}

From source file:org.holodeckb2b.ebms3.pulling.PullConfiguration.java

/**
 * Loads the pulling configuration from file. 
 * //  w  ww  . ja  v  a  2  s. com
 * @param path      Path to the XML document containing the pulling configuration
 * @return          The pulling configuration if successfully loaded, null otherwise
 */
public static PullConfiguration loadFromFile(String path) {
    Log log = LogFactory.getLog(PullConfiguration.class);
    PullConfiguration pullCfg = null;

    log.debug("Loading pulling configuration from XML document in " + path);

    File f = new File(path);

    if (f.exists() && f.canRead()) {
        Serializer serializer = new Persister();
        try {
            pullCfg = serializer.read(PullConfiguration.class, f);
            log.debug("Loaded configuration");
        } catch (Exception ex) {
            log.error("Error while reading configuration from " + path + "! Details: " + ex.getMessage());
        }
    } else
        log.error("Unable to access configuration file" + path + "!");

    return pullCfg;
}

From source file:org.hrva.capture.Capture.java

/**
 * Command-line program to tail a log and then push file to the HRT couch
 * DB.//from   ww  w .jav  a  2  s.com
 *
 * <p>All this does is read properties and invoke run_main</p>
 *
 * @param args arguments
 */
public static void main(String[] args) {
    Log log = LogFactory.getLog(Reformat.class);
    File prop_file = new File("hrtail.properties");
    Properties config = new Properties();
    try {
        config.load(new FileInputStream(prop_file));
    } catch (IOException ex) {
        log.warn("Can't find " + prop_file.getName(), ex);
        try {
            log.debug(prop_file.getCanonicalPath());
        } catch (IOException ex1) {
        }
    }
    Capture capture = new Capture(config);
    try {
        capture.run_main(args);
    } catch (CmdLineException ex1) {
        log.fatal("Invalid Options", ex1);
    } catch (MalformedURLException ex2) {
        log.fatal("Invalid CouchDB URL", ex2);
    } catch (IOException ex3) {
        log.fatal(ex3);
    }
}

From source file:org.hrva.capture.CouchPush.java

/**
 * Command-line program to push a file to the HRT couch DB.
 * <p>All this does is read properties and invoke run_main</p>
 * @param args arguments//from   w  w w  .jav  a  2 s.c  om
 */
public static void main(String[] args) {
    Log log = LogFactory.getLog(CouchPush.class);
    File prop_file = new File("hrtail.properties");
    Properties config = new Properties();
    try {
        config.load(new FileInputStream(prop_file));
    } catch (IOException ex) {
        log.warn("Can't find " + prop_file.getName(), ex);
        try {
            log.debug(prop_file.getCanonicalPath());
        } catch (IOException ex1) {
        }
    }
    CouchPush cp = new CouchPush(config);
    try {
        cp.run_main(args);
    } catch (CmdLineException ex1) {
        log.fatal("Invalid Options", ex1);
    } catch (MalformedURLException ex2) {
        log.fatal("Invalid CouchDB URL", ex2);
    } catch (IOException ex3) {
        log.fatal(ex3);
    }
}