Example usage for java.lang ClassLoader getResourceAsStream

List of usage examples for java.lang ClassLoader getResourceAsStream

Introduction

In this page you can find the example usage for java.lang ClassLoader getResourceAsStream.

Prototype

public InputStream getResourceAsStream(String name) 

Source Link

Document

Returns an input stream for reading the specified resource.

Usage

From source file:org.jenkinsci.plugins.pipeline.maven.WithMavenStepExecution.java

private FilePath setupMavenSpy() throws IOException, InterruptedException {
    if (tempBinDir == null) {
        throw new IllegalStateException("tempBinDir not defined");
    }/*from   w  w w .j a  v a  2s.c  o m*/

    // Mostly for testing / debugging in the IDE
    final String MAVEN_SPY_JAR_URL = "org.jenkinsci.plugins.pipeline.maven.mavenSpyJarUrl";
    String mavenSpyJarUrl = System.getProperty(MAVEN_SPY_JAR_URL);
    InputStream in;
    if (mavenSpyJarUrl == null) {
        String embeddedMavenSpyJarPath = "META-INF/lib/pipeline-maven-spy.jar";
        LOGGER.log(Level.FINE, "Load embedded maven spy jar '" + embeddedMavenSpyJarPath + "'");
        // Don't use Thread.currentThread().getContextClassLoader() as it doesn't show the resources of the plugin
        Class<WithMavenStepExecution> clazz = WithMavenStepExecution.class;
        ClassLoader classLoader = clazz.getClassLoader();
        LOGGER.log(Level.FINE, "Load " + embeddedMavenSpyJarPath + " using classloader "
                + classLoader.getClass() + ": " + classLoader);
        in = classLoader.getResourceAsStream(embeddedMavenSpyJarPath);
        if (in == null) {
            CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
            String msg = "Embedded maven spy jar not found at " + embeddedMavenSpyJarPath
                    + " in the pipeline-maven-plugin classpath. "
                    + "Maven Spy Jar URL can be defined with the system property: '" + MAVEN_SPY_JAR_URL + "'"
                    + "Classloader " + classLoader.getClass() + ": " + classLoader + ". " + "Class "
                    + clazz.getName() + " loaded from "
                    + (codeSource == null ? "#unknown#" : codeSource.getLocation());
            throw new IllegalStateException(msg);
        }
    } else {
        LOGGER.log(Level.FINE, "Load maven spy jar provided by system property '" + MAVEN_SPY_JAR_URL + "': "
                + mavenSpyJarUrl);
        in = new URL(mavenSpyJarUrl).openStream();
    }

    FilePath mavenSpyJarFilePath = tempBinDir.child("pipeline-maven-spy.jar");
    mavenSpyJarFilePath.copyFrom(in);
    return mavenSpyJarFilePath;
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Sample file content: FLURRY_API_KEY=YKN7M4TDXRKXH97PX565
 * Each Flurry API Key corresponds to an Application on Flurry site.  It is absolutely 
  * necessary that the Flurry API Key-value from user's device is correct in order to log to the Flurry application.
  * /*from   ww w  .j a  v a 2 s . co m*/
  * No validation on the API key allows creation of a new Flurry application by client at any time
  * The API key is communicated to the user group who would put the API key name-value pair into 
  * properties file specified by variable flurryFileName below.
  * 
  * If no key-value is found, the default API key is used below.  Default is intended for users of
  * ATT Developer Program.
 */
private void setFlurryApiKey() {
    if (DEBUG) {
        Log.d(TAG, "entered setFlurryApiKey");
    }
    final String flurryFileName = ARODataCollector.ARO_TRACE_ROOTDIR + ARODataCollector.FLURRY_API_KEY_REL_PATH;

    InputStream flurryFileReaderStream = null;
    try {
        final ClassLoader loader = ClassLoader.getSystemClassLoader();

        flurryFileReaderStream = loader.getResourceAsStream(flurryFileName);

        Properties prop = new Properties();
        try {
            if (flurryFileReaderStream != null) {
                prop.load(flurryFileReaderStream);
                mApp.app_flurry_api_key = prop.containsKey(ARODataCollector.FLURRY_API_KEY_NAME)
                        && !prop.getProperty(ARODataCollector.FLURRY_API_KEY_NAME)
                                .equals(AROCollectorUtils.EMPTY_STRING)
                                        ? prop.getProperty(ARODataCollector.FLURRY_API_KEY_NAME).trim()
                                        : mApp.app_flurry_api_key;
                if (DEBUG) {
                    Log.d(TAG, "flurry Property String: " + prop.toString());
                    Log.d(TAG, "flurry app_flurry_api_key: " + mApp.app_flurry_api_key);
                }
            } else {
                if (DEBUG) {
                    Log.d(TAG, "flurryFileReader stream is null.  Using default: " + mApp.app_flurry_api_key);
                }
            }
        } catch (IOException e) {
            Log.d(TAG, e.getClass().getName() + " thrown trying to load file ");
        }
    } finally {
        try {
            if (flurryFileReaderStream != null) {
                flurryFileReaderStream.close();
            }
        } catch (IOException e) {
            //log and exit method-nothing else to do.
            if (DEBUG) {
                Log.d(TAG,
                        "setFlurryApiKey method reached catch in finally method, trying to close flurryFileReader");
            }
        }
        Log.d(TAG, "exiting setFlurryApiKey");
    }
}

From source file:org.apache.oozie.test.XTestCase.java

/**
 * Like {@link #setUp()} but allows skipping cleaning up the database tables.  Most tests should use the other method, unless
 * they specifically don't want to (or can't) clean up the database tables.
 *
 * @param cleanUpDBTables true if should cleanup the database tables, false if not
 * @throws Exception if the test workflow working directory could not be created or there was a problem cleaning the database
 */// w w w . j ava2 s  .com
protected void setUp(boolean cleanUpDBTables) throws Exception {
    RUNNING_TESTCASES.incrementAndGet();
    super.setUp();
    String baseDir = System.getProperty(OOZIE_TEST_DIR, new File("target/test-data").getAbsolutePath());
    String msg = null;
    File f = new File(baseDir);
    if (!f.isAbsolute()) {
        msg = XLog.format("System property [{0}]=[{1}] must be set to an absolute path", OOZIE_TEST_DIR,
                baseDir);
    } else {
        if (baseDir.length() < 4) {
            msg = XLog.format("System property [{0}]=[{1}] path must be at least 4 chars", OOZIE_TEST_DIR,
                    baseDir);
        }
    }
    if (msg != null) {
        System.err.println();
        System.err.println(msg);
        System.exit(-1);
    }
    f.mkdirs();
    if (!f.exists() || !f.isDirectory()) {
        System.err.println();
        System.err.println(XLog.format("Could not create test dir [{0}]", baseDir));
        System.exit(-1);
    }
    hadoopVersion = System.getProperty(HADOOP_VERSION, "0.20.0");
    testCaseDir = createTestCaseDir(this, true);

    //setting up Oozie HOME and Oozie conf directory
    setSystemProperty(Services.OOZIE_HOME_DIR, testCaseDir);
    Services.setOozieHome();
    testCaseConfDir = createTestCaseSubDir("conf");

    // load test Oozie site
    String oozieTestDB = System.getProperty("oozie.test.db", "hsqldb");
    String defaultOozieSize = new File(OOZIE_SRC_DIR,
            "core/src/test/resources/" + oozieTestDB + "-oozie-site.xml").getAbsolutePath();
    String customOozieSite = System.getProperty("oozie.test.config.file", defaultOozieSize);
    File source = new File(customOozieSite);
    if (!source.isAbsolute()) {
        source = new File(OOZIE_SRC_DIR, customOozieSite);
    }
    source = source.getAbsoluteFile();
    InputStream oozieSiteSourceStream = null;
    if (source.exists()) {
        oozieSiteSourceStream = new FileInputStream(source);
    } else {
        // If we can't find it, try using the class loader (useful if we're using XTestCase from outside core)
        URL sourceURL = getClass().getClassLoader().getResource(oozieTestDB + "-oozie-site.xml");
        if (sourceURL != null) {
            oozieSiteSourceStream = sourceURL.openStream();
        } else {
            // If we still can't find it, then exit
            System.err.println();
            System.err.println(XLog.format("Custom configuration file for testing does not exist [{0}]",
                    source.getAbsolutePath()));
            System.err.println();
            System.exit(-1);
        }
    }
    // Copy the specified oozie-site file from oozieSiteSourceStream to the test case dir as oozie-site.xml
    Configuration oozieSiteConf = new Configuration(false);
    oozieSiteConf.addResource(oozieSiteSourceStream);
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream(ConfigurationService.DEFAULT_CONFIG_FILE);
    XConfiguration configuration = new XConfiguration(inputStream);
    String classes = configuration.get(Services.CONF_SERVICE_CLASSES);
    // Disable sharelib service as it cannot find the sharelib jars
    // as maven has target/classes in classpath and not the jar because test phase is before package phase
    oozieSiteConf.set(Services.CONF_SERVICE_CLASSES,
            classes.replaceAll("org.apache.oozie.service.ShareLibService,", ""));
    // Make sure to create the Oozie DB during unit tests
    oozieSiteConf.set(JPAService.CONF_CREATE_DB_SCHEMA, "true");
    File target = new File(testCaseConfDir, "oozie-site.xml");
    oozieSiteConf.writeXml(new FileOutputStream(target));

    File hadoopConfDir = new File(testCaseConfDir, "hadoop-conf");
    hadoopConfDir.mkdir();
    File actionConfDir = new File(testCaseConfDir, "action-conf");
    actionConfDir.mkdir();
    source = new File(OOZIE_SRC_DIR, "core/src/test/resources/hadoop-config.xml");
    InputStream hadoopConfigResourceStream = null;
    if (!source.exists()) {
        // If we can't find it, try using the class loader (useful if we're using XTestCase from outside core)
        URL sourceURL = getClass().getClassLoader().getResource("hadoop-config.xml");
        if (sourceURL != null) {
            hadoopConfigResourceStream = sourceURL.openStream();
        } else {
            // If we still can't find it, then exit
            System.err.println();
            System.err.println(
                    XLog.format("hadoop-config.xml configuration file for testing does not exist [{0}]",
                            source.getAbsolutePath()));
            System.err.println();
            System.exit(-1);
        }
    } else {
        hadoopConfigResourceStream = new FileInputStream(source);
    }
    target = new File(hadoopConfDir, "hadoop-site.xml");
    IOUtils.copyStream(hadoopConfigResourceStream, new FileOutputStream(target));

    if (System.getProperty("oozielocal.log") == null) {
        setSystemProperty("oozielocal.log", "/tmp/oozielocal.log");
    }
    if (System.getProperty("oozie.test.hadoop.security", "simple").equals("kerberos")) {
        System.setProperty("oozie.service.HadoopAccessorService.kerberos.enabled", "true");
    }
    if (System.getProperty("oozie.test.hadoop.minicluster", "true").equals("true")) {
        setUpEmbeddedHadoop(getTestCaseDir());
        // Second cluster is not necessary without the first one
        if (System.getProperty("oozie.test.hadoop.minicluster2", "false").equals("true")) {
            setUpEmbeddedHadoop2();
        }
    }

    if (System.getProperty("oozie.test.db.host") == null) {
        System.setProperty("oozie.test.db.host", "localhost");
    }
    setSystemProperty(ConfigurationService.OOZIE_DATA_DIR, testCaseDir);

    setSystemProperty(HadoopAccessorService.SUPPORTED_FILESYSTEMS, "*");

    if (mrCluster != null) {
        OutputStream os = new FileOutputStream(new File(hadoopConfDir, "core-site.xml"));
        Configuration conf = createJobConfFromMRCluster();
        conf.writeXml(os);
        os.close();
    }

    if (System.getProperty("oozie.test.metastore.server", "false").equals("true")) {
        setupHCatalogServer();
    }

    if (System.getProperty("oozie.test.hive.server.2", "false").equals("true")) {
        setupHiveServer2();
    }

    // Cleanup any leftover database data to make sure we start each test with an empty database
    if (cleanUpDBTables) {
        cleanUpDBTables();
    }
}

From source file:com.thalesgroup.sonar.plugins.tusar.metrics.NewMetrics.java

/**
 * Read the embedded CSV file (or defined by the property) line and add the new metrics which are defined in it.
 *//* w  ww . j  av a 2s.  c  o m*/
private void addNewMetrics() {
    ClassLoader classLoader = getClass().getClassLoader();

    File configFile = NewMetrics.getCSVFilePath() == null ? null : new File(NewMetrics.getCSVFilePath());
    if (configFile != null && configFile.exists()) {
        List<String[]> csvData = null;
        try {
            csvData = Utils.parseIniFile(configFile);
        } catch (FileNotFoundException e) {
            throw new NullPointerException(e.getMessage());
        }

        for (String[] metricsData : csvData) {
            Utils.getLogger().info(metricsData[Constants.METRIC_NAME] + " " + metricsData[Constants.METRIC_TYPE]
                    + " " + metricsData[Constants.METRIC_DOMAIN]);
            NewMetrics.addNewMetric(new Builder(Utils.convertToKeyNorm(metricsData[Constants.METRIC_NAME]),
                    metricsData[Constants.METRIC_NAME],
                    Metric.ValueType.valueOf(metricsData[Constants.METRIC_TYPE].toUpperCase())).setDirection(0)
                            .setQualitative(false).setDomain(metricsData[Constants.METRIC_DOMAIN]).create()
                            .setFormula(new SumChildValuesFormula(false)));
        }
    } else {
        List<String[]> csvData = null;
        try {
            csvData = Utils.parseIniInputStream(classLoader.getResourceAsStream(Constants.DEFAULT_METRICS_CSV));
        } catch (FileNotFoundException e) {
            throw new NullPointerException(e.getMessage());
        }

        for (String[] metricsData : csvData) {
            Utils.getLogger().info(metricsData[Constants.METRIC_NAME] + " " + metricsData[Constants.METRIC_TYPE]
                    + " " + metricsData[Constants.METRIC_DOMAIN]);
            NewMetrics.addNewMetric(new Builder(Utils.convertToKeyNorm(metricsData[Constants.METRIC_NAME]),
                    metricsData[Constants.METRIC_NAME],
                    Metric.ValueType.valueOf(metricsData[Constants.METRIC_TYPE].toUpperCase())).setDirection(0)
                            .setQualitative(false).setDomain(metricsData[Constants.METRIC_DOMAIN]).create()
                            .setFormula(new SumChildValuesFormula(false)));
        }
    }

}

From source file:org.openmrs.module.distrotools.api.impl.DistroToolsServiceImpl.java

/**
 * @see DistroToolsService#installPackage(String, ClassLoader, String)
 *//*  w w w  .  j a  v  a2 s.  co  m*/
public boolean installPackage(String filename, ClassLoader loader, String groupUuid) throws APIException {
    Matcher matcher = Pattern.compile("[\\w/-]+-(\\d+).zip").matcher(filename);
    if (!matcher.matches()) {
        throw new APIException("Filename must match PackageNameWithNoSpaces-X.zip");
    }

    Integer version = Integer.valueOf(matcher.group(1));

    ImportedPackage installed = Context.getService(MetadataSharingService.class)
            .getImportedPackageByGroup(groupUuid);
    if (installed != null && installed.getVersion() >= version) {
        log.info("Metadata package " + filename + " is already installed with version "
                + installed.getVersion());
        return false;
    }

    if (loader.getResource(filename) == null) {
        throw new APIException("Cannot load " + filename + " for group " + groupUuid);
    }

    try {
        PackageImporter metadataImporter = MetadataSharing.getInstance().newPackageImporter();
        metadataImporter.setImportConfig(ImportConfig.valueOf(ImportMode.MIRROR));
        metadataImporter.loadSerializedPackageStream(loader.getResourceAsStream(filename));
        metadataImporter.importPackage();

        log.debug("Loaded metadata package '" + filename + "'");
        return true;

    } catch (Exception ex) {
        throw new APIException("Failed to install metadata package " + filename, ex);
    }
}

From source file:org.alfresco.reporting.ReportingHelper.java

/**
 * Mapping of Alfresco property TYPES onto SQL column definitions.
 * the value of "-" means the Alfresco property will NOT be automatically 
 * mapped into the SQL database. The properties file will be read from classpath
 * There are custom calls for Site, Category, Tags
 * //from   w  w w.j a v  a  2 s. c  o  m
 * @return Properties object
 * @throws Exception 
 */
public Properties getClassToColumnType() throws Exception {
    if (classToColumn == null) {

        //try {
        ClassLoader cl = this.getClass().getClassLoader();

        // get the ibatis resource path from the resource loader. 
        // Tweak this to match our vendor-specific Alfresco type-to-column mapping
        // in order to facilitate differences in DATETIME, TIMESTAMP etc.
        String url = hierarchicalResourceLoader.getResourcePath();
        if (logger.isDebugEnabled()) {
            logger.debug("MyBatis resource path: " + url);
        }
        url = url.substring(0, url.lastIndexOf("/") + 1);
        url += "reporting-model.properties";
        url = "/alfresco/module/org.alfresco.reporting" + url.split("/org.alfresco.reporting")[1];
        if (logger.isDebugEnabled()) {
            logger.debug("Vendor specific mapping path: " + url);
        }

        InputStream is = cl.getResourceAsStream(url);
        Properties p = new Properties();
        p.load(is);
        classToColumn = p;
        if (logger.isInfoEnabled())
            logger.info("classToColumn Loaded!");
        //} catch (IOException e) {
        //   e.printStackTrace();
        //   throw new Exception(e);
        //}
    }

    return classToColumn;
}

From source file:org.georchestra.security.Proxy.java

public void init() throws Exception {
    if (targets != null) {
        for (String url : targets.values()) {
            new URL(url); // test that it is a valid URL
        }//from  w ww.j  a  v a  2 s.c o m
    }
    if (proxyPermissionsFile != null) {
        Closer closer = Closer.create();
        try {
            final ClassLoader classLoader = Proxy.class.getClassLoader();
            InputStream inStream = closer.register(classLoader.getResourceAsStream(proxyPermissionsFile));
            Map<String, Class<?>> aliases = Maps.newHashMap();
            aliases.put(Permissions.class.getSimpleName().toLowerCase(), Permissions.class);
            aliases.put(UriMatcher.class.getSimpleName().toLowerCase(), UriMatcher.class);
            XStreamMarshaller unmarshaller = new XStreamMarshaller();
            unmarshaller.setAliasesByType(aliases);
            setProxyPermissions((Permissions) unmarshaller.unmarshal(new StreamSource(inStream)));
        } finally {
            closer.close();
        }
    }
    // georchestra datadir autoconfiguration
    // dependency injection / properties setter() are made by Spring before
    // init() call
    if ((georchestraConfiguration != null) && (georchestraConfiguration.activated())) {
        logger.info("geOrchestra configuration detected, reconfiguration in progress ...");

        Properties pTargets = georchestraConfiguration.loadCustomPropertiesFile("targets-mapping");

        targets.clear();
        for (String target : pTargets.stringPropertyNames()) {
            targets.put(target, pTargets.getProperty(target));
        }
        logger.info("Done.");
    }
}

From source file:org.apache.axis2.deployment.DeploymentEngine.java

private void populateModule(AxisModule module, URL moduleUrl) throws DeploymentException {
    try {//from  w  w  w  .  j  a  v a 2 s. c  o m
        ClassLoader classLoader = module.getModuleClassLoader();
        InputStream moduleStream = classLoader.getResourceAsStream("META-INF/module.xml");
        if (moduleStream == null) {
            moduleStream = classLoader.getResourceAsStream("meta-inf/module.xml");
        }
        if (moduleStream == null) {
            throw new DeploymentException(
                    Messages.getMessage(DeploymentErrorMsgs.MODULE_XML_MISSING, moduleUrl.toString()));
        }
        ModuleBuilder moduleBuilder = new ModuleBuilder(moduleStream, module, axisConfig);
        moduleBuilder.populateModule();
    } catch (IOException e) {
        throw new DeploymentException(e);
    }
}

From source file:oracle.kv.hadoop.hive.table.TableSerDeBase.java

private String createLocalKVSecurity(final String loginFlnm, final String trustFlnm) throws SerDeException {

    if (loginFlnm == null) {
        return null;
    }/*from   w w  w  .  ja v a2  s.c o  m*/

    if (trustFlnm == null) {
        return null;
    }

    String localLoginFile = loginFlnm;
    String localTrustFile = trustFlnm;

    final File localLoginFileFd = new File(localLoginFile);
    final File localTrustFileFd = new File(localTrustFile);

    if (!localLoginFileFd.exists() || !localTrustFileFd.exists()) {

        final ClassLoader cl = TableSerDeBase.class.getClassLoader();
        final File userSecurityDirFd = new File(USER_SECURITY_DIR);
        if (!userSecurityDirFd.exists()) {
            if (!userSecurityDirFd.mkdirs()) {
                throw new SerDeException(new IOException("failed to create " + userSecurityDirFd));
            }
        }

        try {
            if (!localTrustFileFd.exists()) {
                if (localTrustFileFd.isAbsolute()) {
                    localTrustFile = localTrustFileFd.getName();
                }
                InputStream trustStream = null;
                if (cl != null) {
                    trustStream = cl.getResourceAsStream(localTrustFile);
                } else {
                    trustStream = ClassLoader.getSystemResourceAsStream(localTrustFile);
                }

                final File trustFd = new File(USER_SECURITY_DIR + FILE_SEP + localTrustFile);
                final FileOutputStream trustFlnmFos = new FileOutputStream(trustFd);

                if (trustStream != null) {
                    int nextByte = trustStream.read();
                    while (nextByte != -1) {
                        trustFlnmFos.write(nextByte);
                        nextByte = trustStream.read();
                    }
                }
                trustFlnmFos.close();
            }

            if (!localLoginFileFd.exists()) {
                String loginFileNoPath = localLoginFile;
                if (localLoginFileFd.isAbsolute()) {
                    loginFileNoPath = localLoginFileFd.getName();
                }
                InputStream loginStream = null;
                if (cl != null) {
                    loginStream = cl.getResourceAsStream(loginFileNoPath);
                } else {
                    loginStream = ClassLoader.getSystemResourceAsStream(loginFileNoPath);
                }
                final Properties loginProps = new Properties();
                if (loginStream != null) {
                    loginProps.load(loginStream);
                }

                final String trustFlnmFromLogin = loginProps
                        .getProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY);
                if (trustFlnmFromLogin != null && !trustFlnmFromLogin.equals(localTrustFile)) {

                    /* Replace <path>/trustFlnm with existing trustFlnm. */
                    loginProps.setProperty(KVSecurityConstants.SSL_TRUSTSTORE_FILE_PROPERTY, localTrustFile);
                }
                localLoginFile = USER_SECURITY_DIR + FILE_SEP + loginFileNoPath;
                final File loginFd = new File(localLoginFile);
                final FileOutputStream loginFos = new FileOutputStream(loginFd);
                loginProps.store(loginFos, null);
                loginFos.close();
            }
        } catch (IOException e) {
            throw new SerDeException(e);
        }
    }
    return localLoginFile;
}

From source file:com.flexive.shared.FxSharedUtils.java

/**
 * Get the name of the application server [fleXive] is running on
 *
 * @return name of the application server [fleXive] is running on
 * @since 3.1/*from  ww w  .  j  a  v  a 2  s  . c o  m*/
 */
public synchronized static String getApplicationServerName() {
    if (appserver != null)
        return appserver;
    if (System.getProperty("product.name") != null) {
        // Glassfish 2 / Sun AS
        String ver = System.getProperty("product.name");
        if (System.getProperty("com.sun.jbi.domain.name") != null)
            ver += " (Domain: " + System.getProperty("com.sun.jbi.domain.name") + ")";
        appserver = ver;
    } else if (System.getProperty("glassfish.version") != null) {
        // Glassfish 3+
        appserver = System.getProperty("glassfish.version");
    } else if (System.getProperty("jboss.home.dir") != null) {
        appserver = "JBoss (unknown version)";
        boolean found = false;
        try {
            final Class<?> cls = Class.forName("org.jboss.Version");
            Method m = cls.getMethod("getInstance");
            Object v = m.invoke(null);
            Method pr = cls.getMethod("getProperties");
            Map props = (Map) pr.invoke(v);
            String ver = inspectJBossVersionProperties(props);
            found = true;
            appserver = ver;
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        }
        if (!found) {
            // try JBoss 7 MBean lookup
            try {
                final ObjectName name = new ObjectName("jboss.as:management-root=server");
                final Object version = ManagementFactory.getPlatformMBeanServer().getAttribute(name,
                        "releaseVersion");
                if (version != null) {
                    appserver = "JBoss (" + version + ")";
                    found = true;
                }
            } catch (Exception e) {
                // ignore
            }
        }
        if (!found) {
            //try again with a JBoss 6.x specific locations
            try {
                final ClassLoader jbossCL = Class.forName("org.jboss.Main").getClassLoader();
                if (jbossCL.getResource(JBOSS6_VERSION_PROPERTIES) != null) {
                    Properties prop = new Properties();
                    prop.load(jbossCL.getResourceAsStream(JBOSS6_VERSION_PROPERTIES));
                    if (prop.containsKey("version.name")) {
                        appserver = inspectJBossVersionProperties(prop);
                        //noinspection UnusedAssignment
                        found = true;
                    }
                }
            } catch (ClassNotFoundException e) {
                //ignore
            } catch (IOException e) {
                //ignore
            }
        }
    } else if (System.getProperty("openejb.version") != null) {
        // try to get Jetty version
        String jettyVersion = "";
        try {
            final Class<?> cls = Class.forName("org.mortbay.jetty.Server");
            jettyVersion = " (Jetty " + cls.getPackage().getImplementationVersion() + ")";
        } catch (ClassNotFoundException e) {
            // no Jetty version...
        }
        appserver = "OpenEJB " + System.getProperty("openejb.version") + jettyVersion;
    } else if (System.getProperty("weblogic.home") != null) {
        String server = System.getProperty("weblogic.Name");
        String wlVersion = "";
        try {
            final Class<?> cls = Class.forName("weblogic.common.internal.VersionInfo");
            Method m = cls.getMethod("theOne");
            Object serverVersion = m.invoke(null);
            Method sv = m.invoke(null).getClass().getMethod("getImplementationVersion");
            wlVersion = " " + String.valueOf(sv.invoke(serverVersion));
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        if (StringUtils.isEmpty(server))
            appserver = "WebLogic" + wlVersion;
        else
            appserver = "WebLogic" + wlVersion + " (server: " + server + ")";
    } else if (System.getProperty("org.apache.geronimo.home.dir") != null) {
        String gVersion = "";
        try {
            final Class<?> cls = Class.forName("org.apache.geronimo.system.serverinfo.ServerConstants");
            Method m = cls.getMethod("getVersion");
            gVersion = " " + String.valueOf(m.invoke(null));
            m = cls.getMethod("getBuildDate");
            gVersion = gVersion + " (" + String.valueOf(m.invoke(null)) + ")";
        } catch (ClassNotFoundException e) {
            //ignore
        } catch (NoSuchMethodException e) {
            //ignore
        } catch (InvocationTargetException e) {
            //ignore
        } catch (IllegalAccessException e) {
            //ignore
        }
        appserver = "Apache Geronimo " + gVersion;
    } else {
        appserver = "unknown";
    }
    return appserver;
}