You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by ma...@apache.org on 2015/06/23 19:46:53 UTC

[1/2] incubator-geode git commit: [GEODE-20] Allow REST API to be launched

Repository: incubator-geode
Updated Branches:
  refs/heads/develop 9a0ede304 -> 05e4eb926


[GEODE-20] Allow REST API to be launched


Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/2cae5b71
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/2cae5b71
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/2cae5b71

Branch: refs/heads/develop
Commit: 2cae5b717ee21c1f1c2265a991eefbe1c2eae106
Parents: 9a0ede3
Author: Wes Williams <ww...@pivotal.io>
Authored: Fri Jun 19 22:14:01 2015 -0400
Committer: Wes Williams <ww...@pivotal.io>
Committed: Fri Jun 19 22:14:01 2015 -0400

----------------------------------------------------------------------
 .../gemfire/management/internal/AgentUtil.java  | 150 ++++++++
 .../management/internal/ManagementAgent.java    | 370 ++++++++-----------
 .../gemfire/management/internal/RestAgent.java  | 159 ++++----
 .../management/internal/AgentUtilJUnitTest.java | 106 ++++++
 4 files changed, 479 insertions(+), 306 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/2cae5b71/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java
new file mode 100644
index 0000000..716a1e1
--- /dev/null
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.gemstone.gemfire.management.internal;
+
+import java.io.File;
+
+import org.apache.logging.log4j.Logger;
+
+import com.gemstone.gemfire.internal.lang.StringUtils;
+import com.gemstone.gemfire.internal.logging.LogService;
+
+/**
+ * Hosts common utility methods needed by the management package
+ * 
+ * @author Wes Williams
+ * @since Geode 1.0.0.0
+ *
+ */
+public class AgentUtil {
+
+  private static final Logger logger = LogService.getLogger();
+  private static final String TOOLS_WEB_API_WAR = "/tools/Extensions/gemfire-web-api-";
+  private static final String LIB_WEB_API_WAR = "/lib/gemfire-web-api-";
+  private static final String TOOLS_WEB_WAR = "/tools/Extensions/gemfire-web-";
+  private static final String LIB_WEB_WAR = "/lib/gemfire-web-";
+  private static final String TOOLS_API_WAR = "/tools/Extensions/gemfire-api-";
+  private static final String LIB_API_WAR = "/lib/gemfire-api-";
+  private static final String TOOLS_PULSE_WAR = "/tools/Pulse/pulse.war";
+  private static final String LIB_PULSE_WAR = "/lib/pulse.war";
+
+  private String gemfireVersion = null;
+
+  public AgentUtil(String gemfireVersion) {
+    this.gemfireVersion = gemfireVersion;
+  }
+
+  String getGemFireWebApiWarLocation() {
+    String gemfireHome = getGemFireHome();
+    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+    logger.warn(gemfireHome + TOOLS_WEB_API_WAR + gemfireVersion + ".war");
+
+    if (new File(gemfireHome + TOOLS_WEB_API_WAR + gemfireVersion + ".war").isFile()) {
+      return gemfireHome + TOOLS_WEB_API_WAR + gemfireVersion + ".war";
+    } else if (new File(gemfireHome + LIB_WEB_API_WAR + gemfireVersion + ".war").isFile()) {
+      return gemfireHome + LIB_WEB_API_WAR + gemfireVersion + ".war";
+    } else {
+      return null;
+    }
+  }
+
+  /*
+   * Use the GEMFIRE environment variable to find the GemFire product tree.
+   * First, look in the $GEMFIRE/tools/Management directory Second, look in the
+   * $GEMFIRE/lib directory Finally, if we cannot find Management WAR file then
+   * return null...
+   */
+  String getGemFireWebWarLocation() {
+    String gemfireHome = getGemFireHome();
+    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+
+    if (new File(gemfireHome + TOOLS_WEB_WAR + gemfireVersion + ".war").isFile()) {
+      return gemfireHome + TOOLS_WEB_WAR + gemfireVersion + ".war";
+    } else if (new File(gemfireHome + LIB_WEB_WAR + gemfireVersion + ".war").isFile()) {
+      return gemfireHome + LIB_WEB_WAR + gemfireVersion + ".war";
+    } else {
+      return null;
+    }
+  }
+
+  String getGemfireApiWarLocation() {
+    String gemfireHome = getGemFireHome();
+    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+
+    if (new File(gemfireHome + TOOLS_API_WAR + gemfireVersion + ".war").isFile()) {
+      return gemfireHome + TOOLS_API_WAR + gemfireVersion + ".war";
+    } else if (new File(gemfireHome + LIB_API_WAR + gemfireVersion + ".war").isFile()) {
+      return gemfireHome + LIB_API_WAR + gemfireVersion + ".war";
+    } else {
+      return null;
+    }
+  }
+
+  // Use the GEMFIRE environment variable to find the GemFire product tree.
+  // First, look in the $GEMFIRE/tools/Pulse directory
+  // Second, look in the $GEMFIRE/lib directory
+  // Finally, if we cannot find the Management WAR file then return null...
+  String getPulseWarLocation() {
+    String gemfireHome = getGemFireHome();
+    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+
+    if (new File(gemfireHome + TOOLS_PULSE_WAR).isFile()) {
+      return gemfireHome + TOOLS_PULSE_WAR;
+    } else if (new File(gemfireHome + LIB_PULSE_WAR).isFile()) {
+      return gemfireHome + LIB_PULSE_WAR;
+    } else {
+      return null;
+    }
+  }
+
+  boolean isWebApplicationAvailable(final String warFileLocation) {
+    return !StringUtils.isBlank(warFileLocation);
+  }
+
+  boolean isWebApplicationAvailable(final String... warFileLocations) {
+    for (String warFileLocation : warFileLocations) {
+      if (isWebApplicationAvailable(warFileLocation)) {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+  String getGemFireHome() {
+
+    String gemFireHome = System.getenv("GEMFIRE");
+
+    // Check for empty variable. if empty, then log message and exit HTTP server
+    // startup
+    if (StringUtils.isBlank(gemFireHome)) {
+      gemFireHome = System.getProperty("gemfire.home");
+      logger.info("Reading gemfire.home System Property -> {}", gemFireHome);
+      if (StringUtils.isBlank(gemFireHome)) {
+        logger.info("GEMFIRE environment variable not set; HTTP service will not start.");
+        gemFireHome = null;
+      }
+    }
+    return gemFireHome;
+  }
+
+  boolean isGemfireHomeDefined() {
+    String gemfireHome = getGemFireHome();
+    return !StringUtils.isBlank(gemfireHome);
+  }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/2cae5b71/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
index ebb03e8..72afd5c 100755
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/ManagementAgent.java
@@ -7,7 +7,6 @@
  */
 package com.gemstone.gemfire.management.internal;
 
-import java.io.File;
 import java.io.IOException;
 import java.io.Serializable;
 import java.lang.management.ManagementFactory;
@@ -51,24 +50,24 @@ import com.gemstone.gemfire.management.internal.security.ManagementInterceptor;
 import com.gemstone.gemfire.management.internal.unsafe.ReadOpFileAccessController;
 
 /**
- * Agent implementation that controls the JMX server end points for JMX 
- * clients to connect, such as an RMI server.
+ * Agent implementation that controls the JMX server end points for JMX clients
+ * to connect, such as an RMI server.
  * 
  * The ManagementAgent could be used in a loner or GemFire client to define and
  * control JMX server end points for the Platform MBeanServer and the GemFire
- * MBeans hosted within it. 
+ * MBeans hosted within it.
  *
  * @author VMware, Inc.
  * @since 7.0
  */
-public class ManagementAgent  {
+public class ManagementAgent {
   private static final Logger logger = LogService.getLogger();
-  
+
   /**
    * True if running. Protected by synchronizing on this Manager instance. I
    * used synchronization because I think we'll want to hold the same
-   * synchronize while configuring, starting, and eventually stopping the
-   * RMI server, the hidden management regions (in FederatingManager), etc
+   * synchronize while configuring, starting, and eventually stopping the RMI
+   * server, the hidden management regions (in FederatingManager), etc
    */
   private boolean running = false;
   private Registry registry;
@@ -78,11 +77,12 @@ public class ManagementAgent  {
   private ManagementInterceptor securityInterceptor;
 
   /**
-   * This system property is set to true when the embedded HTTP server is started so that the embedded pulse webapp
-   * can use a local MBeanServer instead of a remote JMX connection.
+   * This system property is set to true when the embedded HTTP server is
+   * started so that the embedded pulse webapp can use a local MBeanServer
+   * instead of a remote JMX connection.
    */
   private static final String PULSE_EMBEDDED_PROP = "pulse.embedded";
-  
+
   public ManagementAgent(DistributionConfig config) {
     this.config = config;
   }
@@ -90,7 +90,7 @@ public class ManagementAgent  {
   public synchronized boolean isRunning() {
     return this.running;
   }
-  
+
   public synchronized boolean isHttpServiceRunning() {
     return isHttpServiceRunning;
   }
@@ -98,44 +98,46 @@ public class ManagementAgent  {
   public synchronized void setHttpServiceRunning(boolean isHttpServiceRunning) {
     this.isHttpServiceRunning = isHttpServiceRunning;
   }
-  
-  private boolean isAPIRestServiceRunning(GemFireCacheImpl cache){
+
+  private boolean isAPIRestServiceRunning(GemFireCacheImpl cache) {
     return (cache != null && cache.getRestAgent() != null && cache.getRestAgent().isRunning());
   }
-  
-  private boolean isServerNode(GemFireCacheImpl cache){
+
+  private boolean isServerNode(GemFireCacheImpl cache) {
     return (cache.getDistributedSystem().getDistributedMember().getVmKind() != DistributionManager.LOCATOR_DM_TYPE
-         && cache.getDistributedSystem().getDistributedMember().getVmKind() != DistributionManager.ADMIN_ONLY_DM_TYPE
-         && !cache.isClient());
+        && cache.getDistributedSystem().getDistributedMember().getVmKind() != DistributionManager.ADMIN_ONLY_DM_TYPE && !cache
+          .isClient());
   }
-  
-  public synchronized void startAgent(GemFireCacheImpl cache){
-    //Do not start Management REST service if developer REST service is already started.
-    
-    if(!isAPIRestServiceRunning(cache)) {
+
+  public synchronized void startAgent(GemFireCacheImpl cache) {
+    // Do not start Management REST service if developer REST service is already
+    // started.
+
+    if (!isAPIRestServiceRunning(cache)) {
       startHttpService(isServerNode(cache));
-    }else {
+    } else {
       if (logger.isDebugEnabled()) {
-        logger.debug("Developer REST APIs webapp is already running, Not Starting M&M REST and pulse!");
+        logger
+            .debug("Developer REST APIs webapp is already running, Not Starting M&M REST and pulse!");
       }
     }
-    
+
     if (!this.running && this.config.getJmxManagerPort() != 0) {
       try {
         configureAndStart();
-      }
-      catch (IOException e) {
+      } catch (IOException e) {
         throw new ManagementException(e);
       }
       this.running = true;
     }
   }
-  
-  public synchronized void stopAgent(){
+
+  public synchronized void stopAgent() {
     stopHttpService();
-    
-    if (!this.running) return;
-    
+
+    if (!this.running)
+      return;
+
     if (logger.isDebugEnabled()) {
       logger.debug("Stopping jmx manager agent");
     }
@@ -145,30 +147,29 @@ public class ManagementAgent  {
     } catch (IOException e) {
       throw new ManagementException(e);
     }
-    
+
     this.running = false;
   }
-  
+
   private Server httpServer;
   private final String GEMFIRE_VERSION = GemFireVersion.getGemFireVersion();
-  
+  private AgentUtil agentUtil = new AgentUtil(GEMFIRE_VERSION);
+
   private void startHttpService(boolean isServer) {
-    final SystemManagementService managementService = (SystemManagementService) ManagementService.getManagementService(
-      CacheFactory.getAnyInstance());
+    final SystemManagementService managementService = (SystemManagementService) ManagementService
+        .getManagementService(CacheFactory.getAnyInstance());
 
     final ManagerMXBean managerBean = managementService.getManagerMXBean();
-    
+
     if (this.config.getHttpServicePort() != 0) {
       if (logger.isDebugEnabled()) {
         logger.debug("Attempting to start HTTP service on port ({}) at bind-address ({})...",
             this.config.getHttpServicePort(), this.config.getHttpServiceBindAddress());
       }
 
-      // GEMFIRE environment variable
-      final String gemfireHome = System.getenv("GEMFIRE");
-
-      // Check for empty variable. if empty, then log message and exit HTTP server startup
-      if (StringUtils.isBlank(gemfireHome)) {
+      // Check for empty variable. if empty, then log message and exit HTTP
+      // server startup
+      if (!agentUtil.isGemfireHomeDefined()) {
         final String message = "GEMFIRE environment variable not set; HTTP service will not start.";
         setStatusMessage(managerBean, message);
         if (logger.isDebugEnabled()) {
@@ -178,16 +179,16 @@ public class ManagementAgent  {
       }
 
       // Find the Management WAR file
-      final String gemfireWar = getGemFireWarLocation(gemfireHome);
-
+      final String gemfireWar = agentUtil.getGemFireWebWarLocation();
       if (gemfireWar == null) {
         if (logger.isDebugEnabled()) {
-          logger.debug("Unable to find GemFire REST API WAR file; the REST API to GemFire will not be exported and accessible.");
+          logger
+              .debug("Unable to find GemFire REST API WAR file; the REST API to GemFire will not be exported and accessible.");
         }
       }
 
       // Find the Pulse WAR file
-      final String pulseWar = getPulseWarLocation(gemfireHome);
+      final String pulseWar = agentUtil.getPulseWarLocation();
 
       if (pulseWar == null) {
         final String message = "Unable to find Pulse web application WAR file; Pulse will not start in embeded mode";
@@ -196,9 +197,9 @@ public class ManagementAgent  {
           logger.debug(message);
         }
       }
-      
-      //Find developer REST WAR file
-      final String gemfireAPIWar =  getGemFireAPIWarLocation(gemfireHome);
+
+      // Find developer REST WAR file
+      final String gemfireAPIWar = agentUtil.getGemFireWebApiWarLocation();
       if (gemfireAPIWar == null) {
         final String message = "Unable to find developer REST web application WAR file; developer REST will not start in embeded mode";
         setStatusMessage(managerBean, message);
@@ -206,161 +207,101 @@ public class ManagementAgent  {
           logger.debug(message);
         }
       }
-      
+
       try {
-        if (isWebApplicationAvailable(gemfireWar, pulseWar, gemfireAPIWar)) {
-          
+        if (agentUtil.isWebApplicationAvailable(gemfireWar, pulseWar, gemfireAPIWar)) {
+
           final String bindAddress = this.config.getHttpServiceBindAddress();
           final int port = this.config.getHttpServicePort();
 
           boolean isRestWebAppAdded = false;
-          
-          this.httpServer = JettyHelper.initJetty(bindAddress, port, 
+
+          this.httpServer = JettyHelper.initJetty(bindAddress, port,
               this.config.getHttpServiceSSLEnabled(),
-              this.config.getHttpServiceSSLRequireAuthentication(), 
-              this.config.getHttpServiceSSLProtocols(),
-              this.config.getHttpServiceSSLCiphers(), 
+              this.config.getHttpServiceSSLRequireAuthentication(),
+              this.config.getHttpServiceSSLProtocols(), this.config.getHttpServiceSSLCiphers(),
               this.config.getHttpServiceSSLProperties());
 
-          if (isWebApplicationAvailable(gemfireWar)) {
-            this.httpServer = JettyHelper.addWebApplication(this.httpServer, "/gemfire", gemfireWar);
+          if (agentUtil.isWebApplicationAvailable(gemfireWar)) {
+            this.httpServer = JettyHelper
+                .addWebApplication(this.httpServer, "/gemfire", gemfireWar);
           }
 
-          if (isWebApplicationAvailable(pulseWar)) {
+          if (agentUtil.isWebApplicationAvailable(pulseWar)) {
             this.httpServer = JettyHelper.addWebApplication(this.httpServer, "/pulse", pulseWar);
           }
-         
-          if(isServer && this.config.getStartDevRestApi()) {
-            if (isWebApplicationAvailable(gemfireAPIWar) ) {
-              this.httpServer = JettyHelper.addWebApplication(this.httpServer, "/gemfire-api", gemfireAPIWar);
+
+          if (isServer && this.config.getStartDevRestApi()) {
+            if (agentUtil.isWebApplicationAvailable(gemfireAPIWar)) {
+              this.httpServer = JettyHelper.addWebApplication(this.httpServer, "/gemfire-api",
+                  gemfireAPIWar);
               isRestWebAppAdded = true;
             }
-          }else {
+          } else {
             final String message = "developer REST web application will not start when start-dev-rest-api is not set and node is not server";
             setStatusMessage(managerBean, message);
             if (logger.isDebugEnabled()) {
               logger.debug(message);
             }
           }
-          
+
           if (logger.isDebugEnabled()) {
             logger.debug("Starting HTTP embedded server on port ({}) at bind-address ({})...",
-                ((ServerConnector)this.httpServer.getConnectors()[0]).getPort(), bindAddress);
+                ((ServerConnector) this.httpServer.getConnectors()[0]).getPort(), bindAddress);
           }
 
           System.setProperty(PULSE_EMBEDDED_PROP, "true");
 
           this.httpServer = JettyHelper.startJetty(this.httpServer);
 
-          // now, that Tomcat has been started, we can set the URL used by web clients to connect to Pulse
-          if (isWebApplicationAvailable(pulseWar)) {
-            managerBean.setPulseURL("http://".concat(getHost(bindAddress)).concat(":").concat(String.valueOf(port))
-              .concat("/pulse/"));
+          // now, that Tomcat has been started, we can set the URL used by web
+          // clients to connect to Pulse
+          if (agentUtil.isWebApplicationAvailable(pulseWar)) {
+            managerBean.setPulseURL("http://".concat(getHost(bindAddress)).concat(":")
+                .concat(String.valueOf(port)).concat("/pulse/"));
           }
-          
-          //set cache property for developer REST service running
-          if(isRestWebAppAdded) {
-            GemFireCacheImpl cache = (GemFireCacheImpl)CacheFactory.getAnyInstance();
+
+          // set cache property for developer REST service running
+          if (isRestWebAppAdded) {
+            GemFireCacheImpl cache = (GemFireCacheImpl) CacheFactory.getAnyInstance();
             cache.setRESTServiceRunning(true);
-            
-            //create region to hold query information (queryId, queryString). Added for the developer REST APIs
+
+            // create region to hold query information (queryId, queryString).
+            // Added for the developer REST APIs
             RestAgent.createParameterizedQueryRegion();
           }
-          
-          //set true for HTTP service running
+
+          // set true for HTTP service running
           setHttpServiceRunning(true);
         }
-      }
-      catch (Exception e) {
-        stopHttpService();//Jetty needs to be stopped even if it has failed to start. Some of the threads are left behind even if server.start() fails due to an exception
-        setStatusMessage(managerBean, "HTTP service failed to start with " + e.getClass().getSimpleName() + " '" + e.getMessage() + "'");
+      } catch (Exception e) {
+        stopHttpService();// Jetty needs to be stopped even if it has failed to
+                          // start. Some of the threads are left behind even if
+                          // server.start() fails due to an exception
+        setStatusMessage(managerBean, "HTTP service failed to start with "
+            + e.getClass().getSimpleName() + " '" + e.getMessage() + "'");
         throw new ManagementException("HTTP service failed to start", e);
       }
-    }
-    else {
-      setStatusMessage(managerBean, "Embedded HTTP server configured not to start (http-service-port=0) or (jmx-manager-http-port=0)");
+    } else {
+      setStatusMessage(managerBean,
+          "Embedded HTTP server configured not to start (http-service-port=0) or (jmx-manager-http-port=0)");
     }
   }
-  
+
   private String getHost(final String bindAddress) throws UnknownHostException {
     if (!StringUtils.isBlank(this.config.getJmxManagerHostnameForClients())) {
       return this.config.getJmxManagerHostnameForClients();
-    }
-    else if (!StringUtils.isBlank(bindAddress)) {
+    } else if (!StringUtils.isBlank(bindAddress)) {
       return InetAddress.getByName(bindAddress).getHostAddress();
-    }
-    else {
+    } else {
       return SocketCreator.getLocalHost().getHostAddress();
     }
   }
 
-  // Use the GEMFIRE environment variable to find the GemFire product tree.
-  // First, look in the $GEMFIRE/tools/Management directory
-  // Second, look in the $GEMFIRE/lib directory
-  // Finally, if we cannot find Management WAR file then return null...
-  private String getGemFireWarLocation(final String gemfireHome) {
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
-
-    if (new File(gemfireHome + "/tools/Extensions/gemfire-web-" + GEMFIRE_VERSION + ".war").isFile()) {
-      return gemfireHome + "/tools/Extensions/gemfire-web-" + GEMFIRE_VERSION + ".war";
-    }
-    else if (new File(gemfireHome + "/lib/gemfire-web-" + GEMFIRE_VERSION + ".war").isFile()) {
-      return gemfireHome + "/lib/gemfire-web-" + GEMFIRE_VERSION + ".war";
-    }
-    else {
-      return null;
-    }
-  }
-
-  // Use the GEMFIRE environment variable to find the GemFire product tree.
-  // First, look in the $GEMFIRE/tools/Pulse directory
-  // Second, look in the $GEMFIRE/lib directory
-  // Finally, if we cannot find the Management WAR file then return null...
-  private String getPulseWarLocation(final String gemfireHome) {
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
-
-    if (new File(gemfireHome + "/tools/Pulse/pulse.war").isFile()) {
-      return gemfireHome + "/tools/Pulse/pulse.war";
-    }
-    else if (new File(gemfireHome + "/lib/pulse.war").isFile()) {
-      return gemfireHome + "/lib/pulse.war";
-    }
-    else {
-      return null;
-    }
-  }
-
-  private String getGemFireAPIWarLocation(final String gemfireHome) {
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
-    if (new File(gemfireHome + "/tools/Extensions/gemfire-api" + GEMFIRE_VERSION + ".war").isFile()) {
-      return gemfireHome + "/tools/Extensions/gemfire-api" + GEMFIRE_VERSION + ".war";
-    }
-    else if (new File(gemfireHome + "/lib/gemfire-api" + GEMFIRE_VERSION + ".war").isFile()) {
-      return gemfireHome + "/lib/gemfire-api" + GEMFIRE_VERSION + ".war";
-    }
-    else {
-      return null;
-    }
-  }
-
   private boolean isRunningInTomcat() {
     return (System.getProperty("catalina.base") != null || System.getProperty("catalina.home") != null);
   }
 
-  private boolean isWebApplicationAvailable(final String warFileLocation) {
-    return !StringUtils.isBlank(warFileLocation);
-  }
-
-  private boolean isWebApplicationAvailable(final String... warFileLocations) {
-    for (String warFileLocation : warFileLocations) {
-      if (isWebApplicationAvailable(warFileLocation)) {
-        return true;
-      }
-    }
-
-    return false;
-  }
-
   private void setStatusMessage(ManagerMXBean mBean, String message) {
     mBean.setPulseURL("");
     mBean.setStatusMessage(message);
@@ -379,7 +320,8 @@ public class ManagementAgent  {
         try {
           this.httpServer.destroy();
         } catch (Exception ignore) {
-          logger.error("Failed to properly release resources held by the HTTP service: {}", ignore.getMessage(), ignore);
+          logger.error("Failed to properly release resources held by the HTTP service: {}",
+              ignore.getMessage(), ignore);
         } finally {
           this.httpServer = null;
           System.clearProperty("catalina.base");
@@ -390,15 +332,18 @@ public class ManagementAgent  {
   }
 
   /**
-   * http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html#gdfvq
-   * https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
-   * https://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector
-   * https://blogs.oracle.com/jmxetc/entry/jmx_connecting_through_firewalls_using
+   * http://docs.oracle.com/javase/6/docs/technotes/guides/management/agent.html
+   * #gdfvq https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
+   * https
+   * ://blogs.oracle.com/jmxetc/entry/building_a_remotely_stoppable_connector
+   * https
+   * ://blogs.oracle.com/jmxetc/entry/jmx_connecting_through_firewalls_using
    */
   private void configureAndStart() throws IOException {
-    // KIRK: I copied this from https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
-    //       we'll need to change this significantly but it's a starting point
-    
+    // KIRK: I copied this from
+    // https://blogs.oracle.com/jmxetc/entry/java_5_premain_rmi_connectors
+    // we'll need to change this significantly but it's a starting point
+
     // get the port for RMI Registry and RMI Connector Server
     final int port = this.config.getJmxManagerPort();
     final String hostname;
@@ -410,42 +355,40 @@ public class ManagementAgent  {
       hostname = this.config.getJmxManagerBindAddress();
       bindAddr = InetAddress.getByName(hostname);
     }
-    
+
     final boolean ssl = this.config.getJmxManagerSSLEnabled();
 
     if (logger.isDebugEnabled()) {
-      logger.debug("Starting jmx manager agent on port {}{}", port, (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : ""));
+      logger.debug("Starting jmx manager agent on port {}{}", port,
+          (bindAddr != null ? (" bound to " + bindAddr) : "") + (ssl ? " using SSL" : ""));
     }
 
     final SocketCreator sc = SocketCreator.createNonDefaultInstance(ssl,
         this.config.getJmxManagerSSLRequireAuthentication(),
-        this.config.getJmxManagerSSLProtocols(),
-        this.config.getJmxManagerSSLCiphers(),
+        this.config.getJmxManagerSSLProtocols(), this.config.getJmxManagerSSLCiphers(),
         this.config.getJmxSSLProperties());
-    RMIClientSocketFactory csf = ssl ? new SslRMIClientSocketFactory() : null;//RMISocketFactory.getDefaultSocketFactory();
-      //new GemFireRMIClientSocketFactory(sc, getLogger());
+    RMIClientSocketFactory csf = ssl ? new SslRMIClientSocketFactory() : null;// RMISocketFactory.getDefaultSocketFactory();
+    // new GemFireRMIClientSocketFactory(sc, getLogger());
     RMIServerSocketFactory ssf = new GemFireRMIServerSocketFactory(sc, bindAddr);
 
     // Following is done to prevent rmi causing stop the world gcs
-    System.setProperty("sun.rmi.dgc.server.gcInterval", Long.toString(Long.MAX_VALUE-1));
-    
+    System.setProperty("sun.rmi.dgc.server.gcInterval", Long.toString(Long.MAX_VALUE - 1));
+
     // Create the RMI Registry using the SSL socket factories above.
-    // In order to use a single port, we must use these factories 
+    // In order to use a single port, we must use these factories
     // everywhere, or nowhere. Since we want to use them in the JMX
     // RMI Connector server, we must also use them in the RMI Registry.
     // Otherwise, we wouldn't be able to use a single port.
     //
     // Start an RMI registry on port <port>.
     registry = LocateRegistry.createRegistry(port, csf, ssf);
-    
+
     // Retrieve the PlatformMBeanServer.
     MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
-    
-    
 
     // Environment map. KIRK: why is this declared as HashMap?
-    final HashMap<String,Object> env = new HashMap<String,Object>();
-    
+    final HashMap<String, Object> env = new HashMap<String, Object>();
+
     boolean integratedSecEnabled = System.getProperty("resource-authenticator") != null;
     if (integratedSecEnabled) {
       securityInterceptor = new ManagementInterceptor(logger);
@@ -467,19 +410,17 @@ public class ManagementAgent  {
         mbs = controller;
       }
     }
-    
-    
-    
-    // Manually creates and binds a JMX RMI Connector Server stub with the 
-    // registry created above: the port we pass here is the port that can  
+
+    // Manually creates and binds a JMX RMI Connector Server stub with the
+    // registry created above: the port we pass here is the port that can
     // be specified in "service:jmx:rmi://"+hostname+":"+port - where the
     // RMI server stub and connection objects will be exported.
-    // Here we choose to use the same port as was specified for the   
+    // Here we choose to use the same port as was specified for the
     // RMI Registry. We can do so because we're using \*the same\* client
     // and server socket factories, for the registry itself \*and\* for this
     // object.
     final RMIServerImpl stub = new RMIJRMPServerImpl(port, csf, ssf, env);
-    
+
     // Create an RMI connector server.
     //
     // As specified in the JMXServiceURL the RMIServer stub will be
@@ -490,24 +431,25 @@ public class ManagementAgent  {
     //
     // The port specified in "service:jmx:rmi://"+hostname+":"+port
     // is the second port, where RMI connection objects will be exported.
-    // Here we use the same port as that we choose for the RMI registry. 
+    // Here we use the same port as that we choose for the RMI registry.
     // The port for the RMI registry is specified in the second part
     // of the URL, in "rmi://"+hostname+":"+port
     //
     // We construct a JMXServiceURL corresponding to what we have done
     // for our stub...
-    final JMXServiceURL url = new JMXServiceURL(
-        "service:jmx:rmi://"+hostname+":"+port+"/jndi/rmi://"+hostname+":"+port+"/jmxrmi");
-    
+    final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + hostname + ":" + port
+        + "/jndi/rmi://" + hostname + ":" + port + "/jmxrmi");
+
     // Create an RMI connector server with the JMXServiceURL
-    //    
-    // KIRK: JDK 1.5 cannot use JMXConnectorServerFactory because of 
+    //
+    // KIRK: JDK 1.5 cannot use JMXConnectorServerFactory because of
     // http://bugs.sun.com/view_bug.do?bug_id=5107423
     // but we're using JDK 1.6
-    cs = new RMIConnectorServer(new JMXServiceURL("rmi",hostname,port),
-          env,stub,mbs) {
+    cs = new RMIConnectorServer(new JMXServiceURL("rmi", hostname, port), env, stub, mbs) {
       @Override
-      public JMXServiceURL getAddress() { return url;}
+      public JMXServiceURL getAddress() {
+        return url;
+      }
 
       @Override
       public synchronized void start() throws IOException {
@@ -521,45 +463,49 @@ public class ManagementAgent  {
         super.start();
       }
     };
-    // This may be the 1.6 way of doing it but the problem is it does not use our "stub".
-    //cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
-       
+    // This may be the 1.6 way of doing it but the problem is it does not use
+    // our "stub".
+    // cs = JMXConnectorServerFactory.newJMXConnectorServer(url, env, mbs);
+
     if (integratedSecEnabled) {
       cs.setMBeanServerForwarder(securityInterceptor.getMBeanServerForwarder());
       logger.info("Starting RMI Connector with Security Interceptor");
-    }  
-    
+    }
+
     cs.start();
     if (logger.isDebugEnabled()) {
       logger.debug("Finished starting jmx manager agent.");
     }
-    //System.out.println("Server started at: "+cs.getAddress());
+    // System.out.println("Server started at: "+cs.getAddress());
 
     // Start the CleanThread daemon... KIRK: not sure what CleanThread is...
     //
-    //final Thread clean = new CleanThread(cs);
-    //clean.start();
+    // final Thread clean = new CleanThread(cs);
+    // clean.start();
   }
-  
-  private static class GemFireRMIClientSocketFactory implements RMIClientSocketFactory, Serializable {
+
+  private static class GemFireRMIClientSocketFactory implements RMIClientSocketFactory,
+      Serializable {
     private static final long serialVersionUID = -7604285019188827617L;
-    
-    private /*final hack to prevent serialization*/ transient SocketCreator sc;
-    
+
+    private/* final hack to prevent serialization */transient SocketCreator sc;
+
     public GemFireRMIClientSocketFactory(SocketCreator sc) {
       this.sc = sc;
     }
 
     @Override
     public Socket createSocket(String host, int port) throws IOException {
-      return this.sc.connectForClient(host, port, 0/*no timeout*/);
+      return this.sc.connectForClient(host, port, 0/* no timeout */);
     }
   };
-  private static class GemFireRMIServerSocketFactory implements RMIServerSocketFactory, Serializable {
+
+  private static class GemFireRMIServerSocketFactory implements RMIServerSocketFactory,
+      Serializable {
     private static final long serialVersionUID = -811909050641332716L;
-    private /*final hack to prevent serialization*/ transient SocketCreator sc;
+    private/* final hack to prevent serialization */transient SocketCreator sc;
     private final InetAddress bindAddr;
-    
+
     public GemFireRMIServerSocketFactory(SocketCreator sc, InetAddress bindAddr) {
       this.sc = sc;
       this.bindAddr = bindAddr;
@@ -570,4 +516,4 @@ public class ManagementAgent  {
       return this.sc.createServerSocket(port, TCPConduit.getBackLog(), this.bindAddr);
     }
   };
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/2cae5b71/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
index 37a767c..cd9d2c6 100755
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/RestAgent.java
@@ -8,12 +8,9 @@
 
 package com.gemstone.gemfire.management.internal;
 
-import java.io.File;
-
 import org.apache.logging.log4j.Logger;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
-import org.springframework.util.Assert;
 
 import com.gemstone.gemfire.cache.AttributesFactory;
 import com.gemstone.gemfire.cache.CacheFactory;
@@ -24,15 +21,15 @@ import com.gemstone.gemfire.distributed.internal.DistributionConfig;
 import com.gemstone.gemfire.internal.GemFireVersion;
 import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
 import com.gemstone.gemfire.internal.cache.InternalRegionArguments;
-import com.gemstone.gemfire.internal.lang.StringUtils;
 import com.gemstone.gemfire.internal.logging.LogService;
 import com.gemstone.gemfire.management.ManagementService;
 
 /**
- * Agent implementation that controls the HTTP server end points used for REST 
+ * Agent implementation that controls the HTTP server end points used for REST
  * clients to connect gemfire data node.
  * 
- * The RestAgent is used to start http service in embedded mode on any non manager data node with developer REST APIs service enabled. 
+ * The RestAgent is used to start http service in embedded mode on any non
+ * manager data node with developer REST APIs service enabled.
  *
  * @author Nilkanth Patel.
  * @since 8.0
@@ -42,42 +39,43 @@ public class RestAgent {
 
   private boolean running = false;
   private final DistributionConfig config;
-  
+
   public RestAgent(DistributionConfig config) {
     this.config = config;
   }
-  
+
   public synchronized boolean isRunning() {
     return this.running;
   }
-  
-  private boolean isManagementRestServiceRunning(GemFireCacheImpl cache){
-    final SystemManagementService managementService = (SystemManagementService) ManagementService.getManagementService(
-        cache);
-    return ( managementService.getManagementAgent() != null && managementService.getManagementAgent().isHttpServiceRunning());
-    
+
+  private boolean isManagementRestServiceRunning(GemFireCacheImpl cache) {
+    final SystemManagementService managementService = (SystemManagementService) ManagementService
+        .getManagementService(cache);
+    return (managementService.getManagementAgent() != null && managementService
+        .getManagementAgent().isHttpServiceRunning());
+
   }
-  
-  public synchronized void start(GemFireCacheImpl cache){
-    if (!this.running 
-        && this.config.getHttpServicePort() != 0 
+
+  public synchronized void start(GemFireCacheImpl cache) {
+    if (!this.running && this.config.getHttpServicePort() != 0
         && !isManagementRestServiceRunning(cache)) {
       try {
         startHttpService();
         this.running = true;
         cache.setRESTServiceRunning(true);
-        
-        //create region to hold query information (queryId, queryString). Added for the developer REST APIs
+
+        // create region to hold query information (queryId, queryString). Added
+        // for the developer REST APIs
         RestAgent.createParameterizedQueryRegion();
-        
-      } catch (RuntimeException e){
+
+      } catch (RuntimeException e) {
         logger.debug(e.getMessage(), e);
       }
     }
-      
+
   }
-  
-  public synchronized void stop(){
+
+  public synchronized void stop() {
     if (this.running) {
       stopHttpService();
       if (logger.isDebugEnabled()) {
@@ -90,92 +88,63 @@ public class RestAgent {
       }
     }
   }
-  
+
   private Server httpServer;
   private final String GEMFIRE_VERSION = GemFireVersion.getGemFireVersion();
-  
-  private String getGemFireAPIWarLocation(final String gemfireHome) {
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
-    if (new File(gemfireHome + "/tools/Extensions/gemfire-api" + GEMFIRE_VERSION + ".war").isFile()) {
-      return gemfireHome + "/tools/Extensions/gemfire-api" + GEMFIRE_VERSION + ".war";
-    }
-    else if (new File(gemfireHome + "/lib/gemfire-api" + GEMFIRE_VERSION + ".war").isFile()) {
-      return gemfireHome + "/lib/gemfire-api" + GEMFIRE_VERSION + ".war";
-    }
-    else {
-      return null;
-    }
-  }
-  
+  private AgentUtil agentUtil = new AgentUtil(GEMFIRE_VERSION);
+
   private boolean isRunningInTomcat() {
     return (System.getProperty("catalina.base") != null || System.getProperty("catalina.home") != null);
   }
-  
-  private boolean isWebApplicationAvailable(final String warFileLocation) {
-    return !StringUtils.isBlank(warFileLocation);
-  }
-  
-  //Start HTTP service in embedded mode
+
+  // Start HTTP service in embedded mode
   public void startHttpService() {
-    //TODO: add a check that will make sure that we start HTTP service on non-manager data node
+    // TODO: add a check that will make sure that we start HTTP service on
+    // non-manager data node
     logger.info("Attempting to start HTTP service on port ({}) at bind-address ({})...",
         this.config.getHttpServicePort(), this.config.getHttpServiceBindAddress());
-      
-    String gemfireHome = System.getenv("GEMFIRE");
-    
-    // Check for empty variable. if empty, then log message and exit HTTP server startup
-    if (StringUtils.isBlank(gemfireHome)) {
-      String gemfire = System.getProperty("gemfire.home");
-      logger.info("Reading gemfire.home System Property -> {}", gemfire);
-      if (StringUtils.isBlank(gemfire)) {
-        logger.info("GEMFIRE environment variable not set; HTTP service will not start.");
-        return;
-      } else {
-        gemfireHome = gemfire;
-      }
-    }
-      
+
     // Find the developer REST WAR file
-    final String gemfireAPIWar =  getGemFireAPIWarLocation(gemfireHome);
-      
-    if(gemfireAPIWar == null){
-      logger.info("Unable to find GemFire Developer REST API WAR file; the Developer REST API for GemFire will not be exported and accessible.");
+    final String gemfireAPIWar = agentUtil.getGemFireWebApiWarLocation();
+    if (gemfireAPIWar == null) {
+      logger
+          .info("Unable to find GemFire Developer REST API WAR file; the Developer REST API for GemFire will not be exported and accessible.");
     }
-      
+
     try {
       // Check if we're already running inside Tomcat
       if (isRunningInTomcat()) {
-        logger.warn("Detected presence of catalina system properties. HTTP service will not be started. To enable the GemFire developer REST API, please deploy the gemfire-web.war file in your application server."); 
-      }
-      else if (isWebApplicationAvailable(gemfireAPIWar)) {
-          
+        logger
+            .warn("Detected presence of catalina system properties. HTTP service will not be started. To enable the GemFire developer REST API, please deploy the gemfire-web.war file in your application server.");
+      } else if (agentUtil.isWebApplicationAvailable(gemfireAPIWar)) {
+
         final String bindAddress = this.config.getHttpServiceBindAddress();
         final int port = this.config.getHttpServicePort();
 
         this.httpServer = JettyHelper.initJetty(bindAddress, port,
             this.config.getHttpServiceSSLEnabled(),
-            this.config.getHttpServiceSSLRequireAuthentication(), 
-            this.config.getHttpServiceSSLProtocols(),
-            this.config.getHttpServiceSSLCiphers(), 
-            this.config.getHttpServiceSSLProperties()
-            );
-          
+            this.config.getHttpServiceSSLRequireAuthentication(),
+            this.config.getHttpServiceSSLProtocols(), this.config.getHttpServiceSSLCiphers(),
+            this.config.getHttpServiceSSLProperties());
+
         this.httpServer = JettyHelper.addWebApplication(httpServer, "/gemfire-api", gemfireAPIWar);
-        
+
         if (logger.isDebugEnabled()) {
           logger.debug("Starting HTTP embedded server on port ({}) at bind-address ({})...",
-              ((ServerConnector)this.httpServer.getConnectors()[0]).getPort(), bindAddress);
+              ((ServerConnector) this.httpServer.getConnectors()[0]).getPort(), bindAddress);
         }
 
         this.httpServer = JettyHelper.startJetty(this.httpServer);
         logger.info("HTTP service started successfully...!!");
       }
-    }catch (Exception e) {
-      stopHttpService();//Jetty needs to be stopped even if it has failed to start. Some of the threads are left behind even if server.start() fails due to an exception
-      throw new RuntimeException("HTTP service failed to start due to "+e.getMessage());
+    } catch (Exception e) {
+      stopHttpService();// Jetty needs to be stopped even if it has failed to
+                        // start. Some of the threads are left behind even if
+                        // server.start() fails due to an exception
+      throw new RuntimeException("HTTP service failed to start due to " + e.getMessage());
     }
   }
-  
+
   private void stopHttpService() {
     if (this.httpServer != null) {
       logger.info("Stopping the HTTP service...");
@@ -187,7 +156,8 @@ public class RestAgent {
         try {
           this.httpServer.destroy();
         } catch (Exception ignore) {
-          logger.error("Failed to properly release resources held by the HTTP service: {}", ignore.getMessage(), ignore);
+          logger.error("Failed to properly release resources held by the HTTP service: {}",
+              ignore.getMessage(), ignore);
         } finally {
           this.httpServer = null;
           System.clearProperty("catalina.base");
@@ -199,16 +169,17 @@ public class RestAgent {
 
   /**
    * This method will create a REPLICATED region named _ParameterizedQueries__.
-   * In developer REST APIs, this region will be used to store the queryId and queryString as a key and value respectively.
+   * In developer REST APIs, this region will be used to store the queryId and
+   * queryString as a key and value respectively.
    */
-  public static void createParameterizedQueryRegion(){
+  public static void createParameterizedQueryRegion() {
     try {
       if (logger.isDebugEnabled()) {
         logger.debug("Starting creation of  __ParameterizedQueries__ region");
       }
-      GemFireCacheImpl cache = (GemFireCacheImpl)CacheFactory.getAnyInstance();
+      GemFireCacheImpl cache = (GemFireCacheImpl) CacheFactory.getAnyInstance();
       if (cache != null) {
-        //cache.getCacheConfig().setPdxReadSerialized(true);
+        // cache.getCacheConfig().setPdxReadSerialized(true);
         final InternalRegionArguments regionArguments = new InternalRegionArguments();
         regionArguments.setIsUsedForMetaRegion(true);
         final AttributesFactory<String, String> attributesFactory = new AttributesFactory<String, String>();
@@ -221,19 +192,19 @@ public class RestAgent {
         attributesFactory.setValueConstraint(String.class);
 
         final RegionAttributes<String, String> regionAttributes = attributesFactory.create();
-        
+
         cache.createVMRegion("__ParameterizedQueries__", regionAttributes, regionArguments);
         if (logger.isDebugEnabled()) {
           logger.debug("Successfully created __ParameterizedQueries__ region");
         }
-      }else {
+      } else {
         logger.error("Cannot create ParameterizedQueries Region as no cache found!");
       }
-    }
-    catch (Exception e) {
+    } catch (Exception e) {
       if (logger.isDebugEnabled()) {
-        logger.debug("Error creating __ParameterizedQueries__ Region with cause {}",e.getMessage(), e);
+        logger.debug("Error creating __ParameterizedQueries__ Region with cause {}",
+            e.getMessage(), e);
       }
     }
   }
-}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/2cae5b71/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java
new file mode 100644
index 0000000..6eb863d
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.gemstone.gemfire.management.internal;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.springframework.util.Assert;
+
+import com.gemstone.junit.UnitTest;
+
+@Category(UnitTest.class)
+public class AgentUtilJUnitTest extends TestCase {
+
+  private AgentUtil agentUtil;
+  private String version;
+
+  public void setUp() {
+    version = getGemfireVersion();
+    agentUtil = new AgentUtil(version);
+  }
+
+  @Test
+  public void testRESTApiExists() {
+    String gemFireWarLocation = agentUtil.getGemFireWebApiWarLocation();
+    Assert.notNull(gemFireWarLocation, "GemFire REST API WAR File was not found");
+  }
+
+  /*
+   * This test should be activated when pulse gets added to Geode
+   */
+  // @Test
+  // public void testPulseWarExists() {
+  // String gemFireWarLocation = agentUtil.getPulseWarLocation();
+  // Assert.notNull(gemFireWarLocation, "Pulse WAR File was not found");
+  // }
+
+  private String getGemfireVersion() {
+    String version = null;
+
+    Properties prop = new Properties();
+    InputStream inputStream = null;
+    String pathPrefix = null;
+    try {
+      pathPrefix = calculatePathPrefixToProjectRoot("gemfire-assembly/");
+      inputStream = new FileInputStream(pathPrefix + "gradle.properties");
+    } catch (FileNotFoundException e1) {
+      try {
+        pathPrefix = calculatePathPrefixToProjectRoot("gemfire-core/");
+        inputStream = new FileInputStream(pathPrefix + "gradle.properties");
+      } catch (FileNotFoundException e) {
+      }
+    }
+
+    if (inputStream != null) {
+      try {
+        prop.load(inputStream);
+        version = prop.getProperty("version");
+      } catch (FileNotFoundException e) {
+      } catch (IOException e) {
+      }
+    }
+    return version;
+  }
+
+  private String calculatePathPrefixToProjectRoot(String subDirectory) {
+    String pathPrefix = "";
+
+    String currentDirectoryPath = new File(".").getAbsolutePath();
+    int gemfireCoreLocationIx = currentDirectoryPath.indexOf(subDirectory);
+    if (gemfireCoreLocationIx < 0) {
+      return pathPrefix;
+    }
+
+    String pathFromRoot = currentDirectoryPath.substring(gemfireCoreLocationIx);
+    int segmentsCount = pathFromRoot.split("/").length - 1;
+
+    for (int i = 0; i < segmentsCount; i++) {
+      pathPrefix = pathPrefix + "../";
+    }
+    return pathPrefix;
+  }
+}


[2/2] incubator-geode git commit: [GEODE-20] - Closing PRs #2 and #9 Changing build.gradle on gemfire-assembly for running junits

Posted by ma...@apache.org.
[GEODE-20] - Closing PRs #2 and #9
Changing build.gradle on gemfire-assembly for running junits


Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/05e4eb92
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/05e4eb92
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/05e4eb92

Branch: refs/heads/develop
Commit: 05e4eb92669f6cff9b22021291c94a2591248041
Parents: 2cae5b7
Author: William Markito <wm...@pivotal.io>
Authored: Tue Jun 23 10:27:30 2015 -0700
Committer: William Markito <wm...@pivotal.io>
Committed: Tue Jun 23 10:27:30 2015 -0700

----------------------------------------------------------------------
 gemfire-assembly/build.gradle                   |  12 +-
 .../src/test/java/AgentUtilJUnitTest.java       | 109 +++++++++++++++++++
 .../gemfire/management/internal/AgentUtil.java  |  26 +++--
 .../management/internal/AgentUtilJUnitTest.java | 106 ------------------
 4 files changed, 133 insertions(+), 120 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/05e4eb92/gemfire-assembly/build.gradle
----------------------------------------------------------------------
diff --git a/gemfire-assembly/build.gradle b/gemfire-assembly/build.gradle
index 7580587..92996ac 100755
--- a/gemfire-assembly/build.gradle
+++ b/gemfire-assembly/build.gradle
@@ -27,17 +27,25 @@ dependencies {
   archives project(':gemfire-core')  
   archives project(':gemfire-web')
   archives project(':gemfire-web-api')
+
+  testCompile project(path: ':gemfire-junit', configuration: 'testOutput')
+  testCompile project(path: ':gemfire-core', configuration: 'testOutput')
 }
 
 sourceSets {
   // need to remove this since we use the dependencies jar out of the install dir
-  test.runtimeClasspath -= configurations.provided
+  //test.runtimeClasspath -= configurations.provided
 }
 
 test {
   // test from the actual classpath not the gradle classpath
   dependsOn installDist
-  classpath += files "$buildDir/install/${distributions.main.baseName}/lib/gemfire-core-dependencies.jar"
+  // @TODO: this doesn't seem to be working need to get basename first.
+  classpath += files "$buildDir/install/apache-geode/lib/gemfire-core-dependencies.jar"
+}
+
+tasks.withType(Test){
+  environment 'GEMFIRE', "$buildDir/install/${distributions.main.baseName}/lib"
 }
 
 task defaultDistributionConfig(type: JavaExec, dependsOn: classes) {

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/05e4eb92/gemfire-assembly/src/test/java/AgentUtilJUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-assembly/src/test/java/AgentUtilJUnitTest.java b/gemfire-assembly/src/test/java/AgentUtilJUnitTest.java
new file mode 100644
index 0000000..925a985
--- /dev/null
+++ b/gemfire-assembly/src/test/java/AgentUtilJUnitTest.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import com.gemstone.gemfire.management.internal.AgentUtil;
+import com.gemstone.junit.IntegrationTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+
+import static org.junit.Assert.*;
+
+@Category(IntegrationTest.class)
+public class AgentUtilJUnitTest {
+
+  private AgentUtil agentUtil;
+  private String version;
+
+  @Before
+  public void setUp() {
+    version = getGemfireVersion();
+    agentUtil = new AgentUtil(version);
+  }
+
+  @Test
+  public void testRESTApiExists() {
+    String gemFireWarLocation = agentUtil.getGemFireWebApiWarLocation();
+    assertNotNull(gemFireWarLocation, "GemFire REST API WAR File was not found");
+  }
+
+  /*
+   * This test should be activated when pulse gets added to Geode
+   */
+  // @Test
+  // public void testPulseWarExists() {
+  // String gemFireWarLocation = agentUtil.getPulseWarLocation();
+  // assertNotNull(gemFireWarLocation, "Pulse WAR File was not found");
+  // }
+
+  private String getGemfireVersion() {
+    String version = null;
+
+    Properties prop = new Properties();
+    InputStream inputStream = null;
+    String pathPrefix = null;
+    try {
+      pathPrefix = calculatePathPrefixToProjectRoot("gemfire-assembly/");
+      inputStream = new FileInputStream(pathPrefix + "gradle.properties");
+    } catch (FileNotFoundException e1) {
+      try {
+        pathPrefix = calculatePathPrefixToProjectRoot("gemfire-core/");
+        inputStream = new FileInputStream(pathPrefix + "gradle.properties");
+      } catch (FileNotFoundException e) {
+      }
+    }
+
+    if (inputStream != null) {
+      try {
+        prop.load(inputStream);
+        version = prop.getProperty("version");
+      } catch (FileNotFoundException e) {
+      } catch (IOException e) {
+      }
+    }
+    return version;
+  }
+
+  private String calculatePathPrefixToProjectRoot(String subDirectory) {
+    String pathPrefix = "";
+
+    String currentDirectoryPath = new File(".").getAbsolutePath();
+    int gemfireCoreLocationIx = currentDirectoryPath.indexOf(subDirectory);
+    if (gemfireCoreLocationIx < 0) {
+      return pathPrefix;
+    }
+
+    String pathFromRoot = currentDirectoryPath.substring(gemfireCoreLocationIx);
+    int segmentsCount = pathFromRoot.split("/").length - 1;
+
+    for (int i = 0; i < segmentsCount; i++) {
+      pathPrefix = pathPrefix + "../";
+    }
+    return pathPrefix;
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/05e4eb92/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java
index 716a1e1..e5b88ad 100644
--- a/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java
+++ b/gemfire-core/src/main/java/com/gemstone/gemfire/management/internal/AgentUtil.java
@@ -42,6 +42,7 @@ public class AgentUtil {
   private static final String LIB_API_WAR = "/lib/gemfire-api-";
   private static final String TOOLS_PULSE_WAR = "/tools/Pulse/pulse.war";
   private static final String LIB_PULSE_WAR = "/lib/pulse.war";
+  public static final String ERROR_VARIABLE_NOT_SET = "The GEMFIRE environment variable must be set!";
 
   private String gemfireVersion = null;
 
@@ -49,9 +50,9 @@ public class AgentUtil {
     this.gemfireVersion = gemfireVersion;
   }
 
-  String getGemFireWebApiWarLocation() {
+  public String getGemFireWebApiWarLocation() {
     String gemfireHome = getGemFireHome();
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+    assert !StringUtils.isBlank(gemfireHome) : ERROR_VARIABLE_NOT_SET;
     logger.warn(gemfireHome + TOOLS_WEB_API_WAR + gemfireVersion + ".war");
 
     if (new File(gemfireHome + TOOLS_WEB_API_WAR + gemfireVersion + ".war").isFile()) {
@@ -69,9 +70,9 @@ public class AgentUtil {
    * $GEMFIRE/lib directory Finally, if we cannot find Management WAR file then
    * return null...
    */
-  String getGemFireWebWarLocation() {
+  public String getGemFireWebWarLocation() {
     String gemfireHome = getGemFireHome();
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+    assert !StringUtils.isBlank(gemfireHome) : ERROR_VARIABLE_NOT_SET;
 
     if (new File(gemfireHome + TOOLS_WEB_WAR + gemfireVersion + ".war").isFile()) {
       return gemfireHome + TOOLS_WEB_WAR + gemfireVersion + ".war";
@@ -82,9 +83,9 @@ public class AgentUtil {
     }
   }
 
-  String getGemfireApiWarLocation() {
+  public String getGemfireApiWarLocation() {
     String gemfireHome = getGemFireHome();
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+    assert !StringUtils.isBlank(gemfireHome) :ERROR_VARIABLE_NOT_SET;
 
     if (new File(gemfireHome + TOOLS_API_WAR + gemfireVersion + ".war").isFile()) {
       return gemfireHome + TOOLS_API_WAR + gemfireVersion + ".war";
@@ -99,9 +100,9 @@ public class AgentUtil {
   // First, look in the $GEMFIRE/tools/Pulse directory
   // Second, look in the $GEMFIRE/lib directory
   // Finally, if we cannot find the Management WAR file then return null...
-  String getPulseWarLocation() {
+  public String getPulseWarLocation() {
     String gemfireHome = getGemFireHome();
-    assert !StringUtils.isBlank(gemfireHome) : "The GEMFIRE environment variable must be set!";
+    assert !StringUtils.isBlank(gemfireHome) : ERROR_VARIABLE_NOT_SET;
 
     if (new File(gemfireHome + TOOLS_PULSE_WAR).isFile()) {
       return gemfireHome + TOOLS_PULSE_WAR;
@@ -112,11 +113,11 @@ public class AgentUtil {
     }
   }
 
-  boolean isWebApplicationAvailable(final String warFileLocation) {
+  public boolean isWebApplicationAvailable(final String warFileLocation) {
     return !StringUtils.isBlank(warFileLocation);
   }
 
-  boolean isWebApplicationAvailable(final String... warFileLocations) {
+  public boolean isWebApplicationAvailable(final String... warFileLocations) {
     for (String warFileLocation : warFileLocations) {
       if (isWebApplicationAvailable(warFileLocation)) {
         return true;
@@ -126,10 +127,11 @@ public class AgentUtil {
     return false;
   }
 
-  String getGemFireHome() {
+  public String getGemFireHome() {
 
     String gemFireHome = System.getenv("GEMFIRE");
 
+    logger.info("GEMFIRE HOME:" + gemFireHome);
     // Check for empty variable. if empty, then log message and exit HTTP server
     // startup
     if (StringUtils.isBlank(gemFireHome)) {
@@ -143,7 +145,7 @@ public class AgentUtil {
     return gemFireHome;
   }
 
-  boolean isGemfireHomeDefined() {
+  public boolean isGemfireHomeDefined() {
     String gemfireHome = getGemFireHome();
     return !StringUtils.isBlank(gemfireHome);
   }

http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/05e4eb92/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java
deleted file mode 100644
index 6eb863d..0000000
--- a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/AgentUtilJUnitTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.gemstone.gemfire.management.internal;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-import junit.framework.TestCase;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.springframework.util.Assert;
-
-import com.gemstone.junit.UnitTest;
-
-@Category(UnitTest.class)
-public class AgentUtilJUnitTest extends TestCase {
-
-  private AgentUtil agentUtil;
-  private String version;
-
-  public void setUp() {
-    version = getGemfireVersion();
-    agentUtil = new AgentUtil(version);
-  }
-
-  @Test
-  public void testRESTApiExists() {
-    String gemFireWarLocation = agentUtil.getGemFireWebApiWarLocation();
-    Assert.notNull(gemFireWarLocation, "GemFire REST API WAR File was not found");
-  }
-
-  /*
-   * This test should be activated when pulse gets added to Geode
-   */
-  // @Test
-  // public void testPulseWarExists() {
-  // String gemFireWarLocation = agentUtil.getPulseWarLocation();
-  // Assert.notNull(gemFireWarLocation, "Pulse WAR File was not found");
-  // }
-
-  private String getGemfireVersion() {
-    String version = null;
-
-    Properties prop = new Properties();
-    InputStream inputStream = null;
-    String pathPrefix = null;
-    try {
-      pathPrefix = calculatePathPrefixToProjectRoot("gemfire-assembly/");
-      inputStream = new FileInputStream(pathPrefix + "gradle.properties");
-    } catch (FileNotFoundException e1) {
-      try {
-        pathPrefix = calculatePathPrefixToProjectRoot("gemfire-core/");
-        inputStream = new FileInputStream(pathPrefix + "gradle.properties");
-      } catch (FileNotFoundException e) {
-      }
-    }
-
-    if (inputStream != null) {
-      try {
-        prop.load(inputStream);
-        version = prop.getProperty("version");
-      } catch (FileNotFoundException e) {
-      } catch (IOException e) {
-      }
-    }
-    return version;
-  }
-
-  private String calculatePathPrefixToProjectRoot(String subDirectory) {
-    String pathPrefix = "";
-
-    String currentDirectoryPath = new File(".").getAbsolutePath();
-    int gemfireCoreLocationIx = currentDirectoryPath.indexOf(subDirectory);
-    if (gemfireCoreLocationIx < 0) {
-      return pathPrefix;
-    }
-
-    String pathFromRoot = currentDirectoryPath.substring(gemfireCoreLocationIx);
-    int segmentsCount = pathFromRoot.split("/").length - 1;
-
-    for (int i = 0; i < segmentsCount; i++) {
-      pathPrefix = pathPrefix + "../";
-    }
-    return pathPrefix;
-  }
-}