/*
 * 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 org.apache.geode.management.internal.cli.commands;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;

import org.apache.geode.internal.GemFireVersion;
import org.apache.geode.internal.util.IOUtils;
import org.apache.geode.test.junit.categories.IntegrationTest;

@Category(IntegrationTest.class)
public class StartMemberUtilsTest {

  @Rule
  public TemporaryFolder temporaryFolder = new TemporaryFolder();

  @Rule
  public RestoreSystemProperties restorer = new RestoreSystemProperties();

  @Test
  public void workingDirDefaultsToMemberName() {
    String workingDir = StartMemberUtils.resolveWorkingDir(null, "server1");
    assertThat(new File(workingDir)).exists();
    assertThat(workingDir).endsWith("server1");
  }

  @Test
  public void workingDirGetsCreatedIfNecessary() throws Exception {
    File workingDir = temporaryFolder.newFolder("foo");
    FileUtils.deleteQuietly(workingDir);
    String workingDirString = workingDir.getAbsolutePath();
    String resolvedWorkingDir = StartMemberUtils.resolveWorkingDir(workingDirString, "server1");
    assertThat(new File(resolvedWorkingDir)).exists();
    assertThat(workingDirString).endsWith("foo");
  }

  @Test
  public void testWorkingDirWithRelativePath() throws Exception {
    Path relativePath = Paths.get("some").resolve("relative").resolve("path");
    assertThat(relativePath.isAbsolute()).isFalse();
    String resolvedWorkingDir =
        StartMemberUtils.resolveWorkingDir(relativePath.toString(), "server1");
    assertThat(resolvedWorkingDir).isEqualTo(relativePath.toAbsolutePath().toString());
  }

  @Test
  public void testReadPid() throws IOException {
    final int expectedPid = 12345;
    File folder = temporaryFolder.newFolder();
    File pidFile = new File(folder, "my.pid");

    assertTrue(pidFile.createNewFile());

    pidFile.deleteOnExit();
    writePid(pidFile, expectedPid);

    final int actualPid = StartMemberUtils.readPid(pidFile);
    assertEquals(expectedPid, actualPid);
  }

  @Test
  public void testGeodeOnClasspathIsFirst() {
    String currentClasspath = System.getProperty("java.class.path");
    String customGeodeCore = "/custom/geode-core-" + GemFireVersion.getGemFireVersion() + ".jar";
    System.setProperty("java.class.path", currentClasspath + ":" + customGeodeCore);

    String[] otherJars = new String[] {"/other/one.jar", "/other/two.jar"};

    String gemfireClasspath = StartMemberUtils.toClasspath(true, otherJars);
    assertThat(gemfireClasspath).startsWith(customGeodeCore);

    gemfireClasspath = StartMemberUtils.toClasspath(false, otherJars);
    assertThat(gemfireClasspath).startsWith(customGeodeCore);
  }

  @Test
  public void testExtensionsJars() throws IOException {

    // when there is no `extensions` directory
    String gemfireClasspath = StartMemberUtils.toClasspath(true, new String[0]);
    assertThat(gemfireClasspath).doesNotContain("extensions");

    if (File.separatorChar == '/') {
      File extensionsDirectory = new File("/tmp/extensions");
      try {

        boolean result = extensionsDirectory.mkdir();
        assertThat(result).isTrue();
        File jarFile = new File("/tmp/extensions/test.jar");
        result = jarFile.createNewFile();
        assertThat(result).isTrue();
        gemfireClasspath =
            StartMemberUtils.toClasspath(true, new String[]{jarFile.getAbsolutePath()});
        assertThat(gemfireClasspath).contains(jarFile.getName());
      } finally {
        FileUtils.deleteDirectory(extensionsDirectory);
      }
    }
  }

  @Test
  public void testAddMaxHeap() {
    List<String> baseCommandLine = new ArrayList<>();

    // Empty Max Heap Option
    StartMemberUtils.addMaxHeap(baseCommandLine, null);
    assertThat(baseCommandLine.size()).isEqualTo(0);

    StartMemberUtils.addMaxHeap(baseCommandLine, "");
    assertThat(baseCommandLine.size()).isEqualTo(0);

    // Only Max Heap Option Set
    StartMemberUtils.addMaxHeap(baseCommandLine, "32g");
    assertThat(baseCommandLine.size()).isEqualTo(3);
    assertThat(baseCommandLine).containsExactly("-Xmx32g", "-XX:+UseConcMarkSweepGC",
        "-XX:CMSInitiatingOccupancyFraction=" + StartMemberUtils.CMS_INITIAL_OCCUPANCY_FRACTION);

    // All Options Set
    List<String> customCommandLine = new ArrayList<>(
        Arrays.asList("-XX:+UseConcMarkSweepGC", "-XX:CMSInitiatingOccupancyFraction=30"));
    StartMemberUtils.addMaxHeap(customCommandLine, "16g");
    assertThat(customCommandLine.size()).isEqualTo(3);
    assertThat(customCommandLine).containsExactly("-XX:+UseConcMarkSweepGC",
        "-XX:CMSInitiatingOccupancyFraction=30", "-Xmx16g");
  }

  private void writePid(final File pidFile, final int pid) throws IOException {
    final FileWriter fileWriter = new FileWriter(pidFile, false);
    fileWriter.write(String.valueOf(pid));
    fileWriter.write("\n");
    fileWriter.flush();
    IOUtils.close(fileWriter);
  }
}

@@ -4252,211 +4252,63 @@
     
-if (File.separatorChar == '/') %7B%0A      File extensionsDirectory = new File(%22/tmp/extensions%22);%0A      try %7B%0A%0A        boolean result = extensionsDirectory.mkdir();%0A        assertThat(result).isTrue();%0A    
+File folder = temporaryFolder.newFolder(%22extensions%22);%0A
     
@@ -4335,25 +4335,17 @@
 ile(
-%22/tmp/extensions/
+folder, %22
 test
@@ -4359,21 +4359,8 @@
 %0A   
-     result =
  jar
@@ -4385,49 +4385,8 @@
 ();%0A
-        assertThat(result).isTrue();%0A    
     
@@ -4407,20 +4407,8 @@
 th =
-%0A           
  Sta
@@ -4451,16 +4451,17 @@
 String%5B%5D
+ 
 %7BjarFile
@@ -4482,20 +4482,16 @@
 th()%7D);%0A
-    
     asse
@@ -4548,95 +4548,8 @@
 ));%0A
-      %7D finally %7B%0A        FileUtils.deleteDirectory(extensionsDirectory);%0A      %7D%0A    %7D
 %0A  %7D

Use JUnit TemporaryFolder rule for the test