List of usage examples for org.apache.commons.logging Log warn
void warn(Object message);
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;// w w w.j a v a 2 s. com 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;// ww w .j a va 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.hyperic.hq.plugin.netdevice.NetworkDeviceDetector.java
protected List discoverInterfaces(ConfigResponse serverConfig) throws PluginException { Log log = getLog(); List services = new ArrayList(); String type = getServiceTypeName(SVC_NAME); if (!hasInterfaceService()) { log.debug("Skipping discovery of " + type); return services; }/*from www . j a va 2s.co m*/ String[] keys = getCustomPropertiesSchema(type).getOptionNames(); HashMap cpropColumns = new HashMap(); for (int i = 0; i < keys.length; i++) { String key = keys[i]; if (Arrays.binarySearch(FILTER_PROPS, key) != -1) { continue; } try { cpropColumns.put(key, getIfColumn(key)); } catch (PluginException e) { log.warn("Error getting '" + key + "': " + e.getMessage()); } } String columnName = serverConfig.getValue(PROP_IF_IX); if (columnName == null) { columnName = IF_DESCR; } Map interfaces = getIfColumn(columnName); log.debug("Found " + interfaces.size() + " interfaces using " + columnName); String descrColumn = columnName.equals(IF_DESCR) ? IF_NAME : IF_DESCR; Map descriptions; try { descriptions = getIfColumn(descrColumn); } catch (PluginException e) { descriptions = new HashMap(); String msg = "Error getting descriptions from " + descrColumn + ": " + e; log.warn(msg); } List ip_if_ix = getColumn(IP_IF_IX); HashMap ips = new HashMap(); HashMap netmasks = new HashMap(); final String IF_IX_OID = SNMPClient.getOID(IP_IF_IX) + "."; final String NETMASK_OID = SNMPClient.getOID(IP_NETMASK) + "."; String ip, netmask; for (int i = 0; i < ip_if_ix.size(); i++) { SNMPValue value = (SNMPValue) ip_if_ix.get(i); String oid = value.getOID(); String ix = value.toString(); if (oid.startsWith(IF_IX_OID)) { ip = oid.substring(IF_IX_OID.length()); ips.put(ix, ip); try { netmask = this.session.getSingleValue(NETMASK_OID + ip).toString(); netmasks.put(ix, netmask); } catch (SNMPException e) { log.debug("Failed to get netmask for " + ip); } } } for (Iterator it = interfaces.entrySet().iterator(); it.hasNext();) { ConfigResponse config = new ConfigResponse(); ConfigResponse cprops = new ConfigResponse(); Map.Entry entry = (Map.Entry) it.next(); String ix = (String) entry.getKey(); String name = (String) entry.getValue(); String mac = null; ServiceResource service = createServiceResource(SVC_NAME); config.setValue(PROP_IF, name); config.setValue(PROP_IF_IX, columnName); service.setProductConfig(config); // required to auto-enable metric service.setMeasurementConfig(); for (int j = 0; j < keys.length; j++) { String key = keys[j]; Map data = (Map) cpropColumns.get(key); if (data == null) { continue; } String val = (String) data.get(ix); if (val == null) { continue; } cprops.setValue(key, val); if (key.equals(IF_MAC)) { mac = val; } } ip = (String) ips.get(ix); netmask = (String) netmasks.get(ix); if (ip == null) { ip = "0.0.0.0"; } if (netmask == null) { netmask = "0.0.0.0"; } cprops.setValue(PROP_IP, ip); cprops.setValue(PROP_NETMASK, netmask); service.setCustomProperties(cprops); // Might be more than 1 interface w/ the same name, // so append the mac address to make it unique... name = name + " " + SVC_NAME; if ((mac != null) && !mac.equals("0:0:0:0:0:0")) { name += " (" + mac + ")"; } service.setServiceName(name); Object obj = descriptions.get(ix); if (obj != null) { service.setDescription(obj.toString()); } services.add(service); } return services; }
From source file:org.hyperic.hq.ui.action.resource.service.inventory.ViewServiceAction.java
/** * Retrieve this data and store it in the <code>ServerForm</code>: * /*w w w.j a v a 2 s.c om*/ */ public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Log log = LogFactory.getLog(ViewServiceAction.class.getName()); try { ServiceValue service = (ServiceValue) RequestUtils.getResource(request); Integer sessionId = RequestUtils.getSessionId(request); AppdefEntityID entityId = service.getEntityId(); PageControl pcg = RequestUtils.getPageControl(request, "psg", "png", "sog", "scg"); List<AppdefGroupValue> groups = appdefBoss.findAllGroupsMemberInclusive(sessionId.intValue(), pcg, service.getEntityId()); // check to see if this thing is a platform service if (service.getServer().getServerType().getVirtual()) { // find the platform resource and add it to the request scope try { PlatformValue pv = appdefBoss.findPlatformByDependentID(sessionId.intValue(), entityId); request.setAttribute(Constants.PARENT_RESOURCE_ATTR, pv); } catch (PermissionException pe) { // TODO Would like to able to fall back and grab the name // through other means // which isn't easily done right now. Only thing we should // prevent // in the case of an error is plain text instead of a link. log.error("insufficient permissions for parent platform ", pe); RequestUtils.setError(request, "resource.service.inventory.error.ViewParentPlatformPermission"); request.setAttribute(Constants.PRODUCT_CONFIG_OPTIONS, new ArrayList()); request.setAttribute(Constants.PRODUCT_CONFIG_OPTIONS_COUNT, new Integer(0)); request.setAttribute(Constants.MONITOR_CONFIG_OPTIONS, new ArrayList()); request.setAttribute(Constants.MONITOR_CONFIG_OPTIONS_COUNT, new Integer(0)); return null; } } request.setAttribute(Constants.ALL_RESGRPS_ATTR, groups); if (service == null) { RequestUtils.setError(request, "resource.service.error.ServiceNotFound"); return null; } // create and initialize the remove resource groups form RemoveResourceGroupsForm rmGroupsForm = new RemoveResourceGroupsForm(); rmGroupsForm.setRid(service.getId()); rmGroupsForm.setType(new Integer(service.getEntityId().getType())); int psg = RequestUtils.getPageSize(request, "psg"); rmGroupsForm.setPsg(new Integer(psg)); request.setAttribute(Constants.RESOURCE_REMOVE_GROUPS_MEMBERS_FORM_ATTR, rmGroupsForm); log.debug("AppdefEntityID = " + entityId.toString()); ConfigSchema config = new ConfigSchema(); ConfigResponse oldResponse = new ConfigResponse(); boolean editConfig = false; try { oldResponse = productBoss.getMergedConfigResponse(sessionId.intValue(), ProductPlugin.TYPE_PRODUCT, entityId, false); config = productBoss.getConfigSchema(sessionId.intValue(), entityId, ProductPlugin.TYPE_PRODUCT, oldResponse); editConfig = true; } catch (ConfigFetchException e) { log.warn("Managed Exception ConfigFetchException caught " + e.toString()); } catch (PluginNotFoundException e) { log.warn("Managed Exception PluginNotFoundException caught " + e.toString()); } List<ConfigValues> uiProductOptions = ActionUtils.getConfigValues(config, oldResponse); request.setAttribute(Constants.PRODUCT_CONFIG_OPTIONS, uiProductOptions); request.setAttribute(Constants.PRODUCT_CONFIG_OPTIONS_COUNT, new Integer(uiProductOptions.size())); config = new ConfigSchema(); oldResponse = new ConfigResponse(); try { oldResponse = productBoss.getMergedConfigResponse(sessionId.intValue(), ProductPlugin.TYPE_MEASUREMENT, entityId, false); config = productBoss.getConfigSchema(sessionId.intValue(), entityId, ProductPlugin.TYPE_MEASUREMENT, oldResponse); } catch (ConfigFetchException e) { // do nothing } catch (PluginNotFoundException e) { // do nothing } setUIOptions(service, request, config, oldResponse); config = new ConfigSchema(); oldResponse = productBoss.getMergedConfigResponse(sessionId.intValue(), ProductPlugin.TYPE_CONTROL, entityId, false); try { config = productBoss.getConfigSchema(sessionId.intValue(), entityId, ProductPlugin.TYPE_CONTROL, oldResponse); } catch (PluginNotFoundException e) { // do nothing } List<ConfigValues> uiControlOptions = ActionUtils.getConfigValues(config, oldResponse); request.setAttribute(Constants.CONTROL_CONFIG_OPTIONS, uiControlOptions); request.setAttribute(Constants.CONTROL_CONFIG_OPTIONS_COUNT, new Integer(uiControlOptions.size())); request.setAttribute(Constants.AUTO_INVENTORY, new Boolean(service.getServer().getRuntimeAutodiscovery())); if (!editConfig) RequestUtils.setError(request, "resource.common.inventory.error.serverConfigNotSet", "configServer"); request.setAttribute(Constants.EDIT_CONFIG, new Boolean(editConfig)); setConfigModifier(request, entityId); return null; } catch (ApplicationException e) { log.error("unable to retrieve configuration properties ", e); RequestUtils.setError(request, "resource.common.inventory.error.configRetrieveError"); request.setAttribute(Constants.PRODUCT_CONFIG_OPTIONS, new ArrayList()); request.setAttribute(Constants.PRODUCT_CONFIG_OPTIONS_COUNT, new Integer(0)); request.setAttribute(Constants.MONITOR_CONFIG_OPTIONS, new ArrayList()); request.setAttribute(Constants.MONITOR_CONFIG_OPTIONS_COUNT, new Integer(0)); return null; } }
From source file:org.hyperic.util.file.match.Matcher.java
/** * Determine if the dir is on a filesystem that we should * be searching.//from w ww .j a va2s. com * @param dir The name of the directory. * @param fstypes The filesystem types we're supposed to search. * @param filesystems The filesystems that sigar detected. * @param log The log to use for errors and warnings. * @return true if the directory should be included in the search, * false otherwise. */ private boolean isFSTypeMatch(String dir, int fstypes, FileSystem[] filesystems, Log log) { String longestMatch = ""; int longestMatchIndex = -1; String absPath = (new File(dir)).getAbsolutePath(); String fsMountPoint; if (filesystems == null) { if (log != null) { log.error("matcher: filesystems array was never initialized."); } throw new IllegalArgumentException("filesystems array was never " + "initialized."); } for (int i = 0; i < filesystems.length; i++) { fsMountPoint = filesystems[i].getDirName(); if (absPath.startsWith(fsMountPoint) && fsMountPoint.length() > longestMatch.length()) { longestMatch = fsMountPoint; longestMatchIndex = i; } } if (longestMatchIndex == -1) { if (log != null) { log.warn("Directory " + dir + " did not match " + "any filesystems, it will not be searched."); } return false; } return isCandidateFS(fstypes, filesystems[longestMatchIndex], log); }
From source file:org.hyperic.util.file.match.Matcher.java
/** * Determine if the given filesystem is OK to search, based on * the value of fstype which tells us what filesystem types we * are supposed to search.// ww w . j av a 2 s .c o m */ public boolean isCandidateFS(int fstype, FileSystem fs, Log log) { switch (fs.getType()) { case FileSystem.TYPE_UNKNOWN: if (log != null) { log.warn("Encountered UNKNOWN filesystem (device=" + fs.getDevName() + "): " + fs.getDirName()); } return false; case FileSystem.TYPE_NONE: if (log != null) { log.warn("Encountered NONE filesystem (device=" + fs.getDevName() + "): " + fs.getDirName()); } return false; case FileSystem.TYPE_LOCAL_DISK: return (fstype == MatcherConfig.FS_ALL || fstype == MatcherConfig.FS_LOCAL); case FileSystem.TYPE_NETWORK: return (fstype == MatcherConfig.FS_ALL || fstype == MatcherConfig.FS_NETWORK); case FileSystem.TYPE_RAM_DISK: case FileSystem.TYPE_CDROM: case FileSystem.TYPE_SWAP: return false; default: if (log != null) { log.warn("Encountered filesystem with invalid type (" + fs.getType() + ") (device=" + fs.getDevName() + "): " + fs.getDirName()); } return false; } }
From source file:org.hyperic.util.file.match.Matcher.java
/** * Get the matches for this search.//from ww w . j av a 2 s . c o m * @return A Map representing the matches. The keys in the Map are * the keys that each MatchSelector in the MatcherConfig was * initialized with in its constructor. The values are Lists, where * each element in the List is a String representing the full path * of the matched path. * @exception MatcherInterruptedException If the search was interrupted * before it could be completed. In this case, you can get the matches * so far by calling getMatchesSoFar on the MatcherInterruptedException * object. * @exception SigarException If an error occurs reading the available * filesystems - this can only happen if the config's getFSTypes returns * a value other than MatcherConfig.FS_ALL. */ public synchronized MatchResults getMatches(MatcherConfig config) throws MatcherInterruptedException, SigarException { int i, j; List scanners; MatcherScanner scanner; MatchResults results = new MatchResults(); File f; Log log = config.getLog(); FileSystem[] filesystems = null; filesystems = loadFilesystems(config); scanners = initScanners(config, filesystems, results); for (i = 0; i < scanners.size(); i++) { scanner = (MatcherScanner) scanners.get(i); scanner.initMatches(results.matches); try { scanner.doScan(); } catch (MatcherInterruptedException mie) { mie.setMatchesSoFar(scanner.getMatches()); if (log != null) { log.warn("matcher: search interrupted."); } throw mie; } catch (Exception e) { // huh? scanner.addError(new MatcherException("matcher: search error", e)); if (log != null) { log.error("matcher: search error: " + e, e); } } results.matches = scanner.getMatches(); if (log != null) { log.debug("results.matches=" + results.matches); } results.errors.addAll(scanner.getErrors()); } return results; }
From source file:org.inwiss.platform.common.util.ConvertUtil.java
/** * Converts string to byte array according to specified encoding * * @param content String to convert to array * @param encoding Encoding string, if <code>null</code> default is used * @return byte array//www . j av a2s .c o m */ public static byte[] convertToByteArray(String content, String encoding) { Log log = LogFactory.getLog(ConvertUtil.class); if (content == null) { return null; } if (encoding == null) { encoding = Constants.DEFAULT_ENCODING; } if (log.isDebugEnabled()) { log.debug("Converting to byte array using: " + encoding); } byte[] value; try { value = content.getBytes(encoding); } catch (UnsupportedEncodingException ex) { if (log.isWarnEnabled()) { log.warn(ex); } return content.getBytes(); } return value; }
From source file:org.jboss.netty.logging.CommonsLoggerTest.java
@Test public void testWarn() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.warn("a"); replay(mock);//from w w w . ja va2s. c om InternalLogger logger = new CommonsLogger(mock, "foo"); logger.warn("a"); verify(mock); }
From source file:org.jboss.set.aphrodite.common.Utils.java
public static void logWarnMessage(Log log, String message) { if (log.isWarnEnabled()) log.warn(message); }