org.apache.commons.lang3.SystemUtils Java Examples

The following examples show how to use org.apache.commons.lang3.SystemUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SysUtils.java    From mvn-golang with Apache License 2.0 6 votes vote down vote up
@Nullable
public static String findGoSdkOsType() {
  final String result;
  if (SystemUtils.IS_OS_WINDOWS) {
    result = "windows";
  } else if (SystemUtils.IS_OS_FREE_BSD) {
    result = "freebsd";
  } else if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) {
    result = "darwin";
  } else if (SystemUtils.IS_OS_LINUX) {
    result = "linux";
  } else {
    result = null;
  }
  return result;
}
 
Example #2
Source File: MyPdfUtils.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 获取 pdfdecrypt.exe 文件路径
 *
 * @return
 * @throws IOException
 */
private static String getPdfPdfdecryptExec() {

    //命令行模式,只需要两个文件即可
    String exec1 = "/pdfdecrypt.exe";
    String exec2 = "/license.dat";

    String tempPath =
            SystemUtils.getJavaIoTmpDir()
                    + File.separator + MyConstants.JarTempDir + File.separator;

    String exec1Path = tempPath + exec1;
    String exec2Path = tempPath + exec2;

    //如果已经拷贝过,就不用再拷贝了
    if (!Files.exists(Paths.get(exec1Path)))
        MyFileUtils.copyResourceFileFromJarLibToTmpDir(exec1);

    if (!Files.exists(Paths.get(exec2Path)))
        MyFileUtils.copyResourceFileFromJarLibToTmpDir(exec2);


    return exec1Path;
}
 
Example #3
Source File: FilesystemUtil.java    From elasticsearch-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Set the 755 permissions on the given script.
 * @param config - the instance config
 * @param scriptName - the name of the script (located in the bin directory) to make executable
 */
public static void setScriptPermission(InstanceConfiguration config, String scriptName)
{
    if (SystemUtils.IS_OS_WINDOWS)
    {
        // we do not have file permissions on windows
        return;
    }
    if (VersionUtil.isEqualOrGreater_7_0_0(config.getClusterConfiguration().getVersion())) {
        // ES7 and above is packaged as a .tar.gz, and as such the permissions are preserved
        return;
    }
    
    CommandLine command = new CommandLine("chmod")
            .addArgument("755")
            .addArgument(String.format("bin/%s", scriptName));
    ProcessUtil.executeScript(config, command);

    command = new CommandLine("sed")
            .addArguments("-i''")
            .addArgument("-e")
            .addArgument("1s:.*:#!/usr/bin/env bash:", false)
            .addArgument(String.format("bin/%s", scriptName));
    ProcessUtil.executeScript(config, command);
}
 
Example #4
Source File: GoConfigServiceTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrowIfCruiseHasNoReadPermissionOnArtifactsDir() throws Exception {
    if (SystemUtils.IS_OS_WINDOWS) {
        return;
    }

    File artifactsDir = FileUtil.createTempFolder();
    artifactsDir.setReadable(false, false);
    cruiseConfig.setServerConfig(new ServerConfig(artifactsDir.getAbsolutePath(), new SecurityConfig()));
    expectLoad(cruiseConfig);

    try {
        goConfigService.initialize();
        fail("should throw when cruise has no read permission on artifacts dir " + artifactsDir.getAbsolutePath());
    } catch (Exception e) {
        assertThat(e.getMessage(), is("Cruise does not have read permission on " + artifactsDir.getAbsolutePath()));
    } finally {
        FileUtils.deleteQuietly(artifactsDir);
    }

}
 
Example #5
Source File: LauncherUtils.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if there is a konduit server running with the given application id.
 * @param applicationId application id of the konduit server.
 * @return true if the server process exists, false otherwise.
 */
public static boolean isProcessExists(String applicationId) {
    List<String> args;

    if(SystemUtils.IS_OS_WINDOWS) {
        args = Arrays.asList("WMIC", "PROCESS", "WHERE", "\"CommandLine like '%serving.id=" + applicationId + "' and name!='wmic.exe'\"", "GET", "CommandLine", "/VALUE");
    } else {
        args = Arrays.asList("sh", "-c", "ps ax | grep \"Dserving.id=" + applicationId + "$\"");
    }

    String output = "";
    try {
        Process process = new ProcessBuilder(args).start();
        output = IOUtils.toString(process.getInputStream(), StandardCharsets.UTF_8);
    } catch (Exception exception) {
        log.error("An error occurred while checking for existing processes:", exception);
        System.exit(1);
    }

    return output.trim()
            .replace(System.lineSeparator(), "")
            .matches("(.*)Dserving.id=" + applicationId);
}
 
Example #6
Source File: ExceptionUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Produces a <code>List</code> of stack frames - the message
 * is not included. Only the trace of the specified exception is
 * returned, any caused by trace is stripped.</p>
 *
 * <p>This works in most cases - it will only fail if the exception
 * message contains a line that starts with:
 * <code>&quot;&nbsp;&nbsp;&nbsp;at&quot;.</code></p>
 * 
 * @param t is any throwable
 * @return List of stack frames
 */
static List<String> getStackFrameList(final Throwable t) {
    final String stackTrace = getStackTrace(t);
    final String linebreak = SystemUtils.LINE_SEPARATOR;
    final StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
    final List<String> list = new ArrayList<String>();
    boolean traceStarted = false;
    while (frames.hasMoreTokens()) {
        final String token = frames.nextToken();
        // Determine if the line starts with <whitespace>at
        final int at = token.indexOf("at");
        if (at != -1 && token.substring(0, at).trim().isEmpty()) {
            traceStarted = true;
            list.add(token);
        } else if (traceStarted) {
            break;
        }
    }
    return list;
}
 
Example #7
Source File: AppiumServiceBuilder.java    From java-client with Apache License 2.0 6 votes vote down vote up
private static File findMainScript() {
    File npm = findNpm();
    List<String> cmdLine = SystemUtils.IS_OS_WINDOWS
            // npm is a batch script, so on windows we need to use cmd.exe in order to execute it
            ? Arrays.asList("cmd.exe", "/c", String.format("\"%s\" root -g", npm.getAbsolutePath()))
            : Arrays.asList(npm.getAbsolutePath(), "root", "-g");
    ProcessBuilder pb = new ProcessBuilder(cmdLine);
    String nodeModulesRoot;
    try {
        nodeModulesRoot = IOUtils.toString(pb.start().getInputStream(), StandardCharsets.UTF_8).trim();
    } catch (IOException e) {
        throw new InvalidServerInstanceException(
                "Cannot retrieve the path to the folder where NodeJS modules are located", e);
    }
    File mainAppiumJs = Paths.get(nodeModulesRoot, APPIUM_PATH_SUFFIX.toString()).toFile();
    if (!mainAppiumJs.exists()) {
        throw new InvalidServerInstanceException(APPIUM_JS_NOT_EXIST_ERROR.apply(mainAppiumJs));
    }
    return mainAppiumJs;
}
 
Example #8
Source File: SpringBootContractTest.java    From moneta with Apache License 2.0 6 votes vote down vote up
public void run() {
	try {
	executor = new DaemonExecutor();
	resultHandler = new DefaultExecuteResultHandler();
	String javaHome = System.getProperty("java.home");
	String userDir = System.getProperty("user.dir");
	
	executor.setStreamHandler(new PumpStreamHandler(System.out));
	watchdog = new ExecuteWatchdog(15000);
	executor.setWatchdog(watchdog);
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version"));
	executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR 
			+ "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe")
		.addArgument("-jar")
		.addArgument(userDir + "/../moneta-springboot/target/moneta-springboot-" + ContractTestSuite.getProjectVersion() + ".jar"));
	
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example #9
Source File: MultiLineToStringStyleTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testObject() {
    Integer i3 = new Integer(3);
    Integer i4 = new Integer(4);
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  <null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) null).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(i3).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) null).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=3" + SystemUtils.LINE_SEPARATOR + "  b=4" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<Integer>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3, false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<size=0>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=[]" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<size=0>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a={}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<size=0>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a={}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
}
 
Example #10
Source File: ExceptionUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * <p>Produces a <code>List</code> of stack frames - the message
 * is not included. Only the trace of the specified exception is
 * returned, any caused by trace is stripped.</p>
 *
 * <p>This works in most cases - it will only fail if the exception
 * message contains a line that starts with:
 * <code>&quot;&nbsp;&nbsp;&nbsp;at&quot;.</code></p>
 * 
 * @param t is any throwable
 * @return List of stack frames
 */
static List<String> getStackFrameList(Throwable t) {
    String stackTrace = getStackTrace(t);
    String linebreak = SystemUtils.LINE_SEPARATOR;
    StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
    List<String> list = new ArrayList<String>();
    boolean traceStarted = false;
    while (frames.hasMoreTokens()) {
        String token = frames.nextToken();
        // Determine if the line starts with <whitespace>at
        int at = token.indexOf("at");
        if (at != -1 && token.substring(0, at).trim().length() == 0) {
            traceStarted = true;
            list.add(token);
        } else if (traceStarted) {
            break;
        }
    }
    return list;
}
 
Example #11
Source File: DefaultFileUploadService.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public Boolean deleteFile(String fileName)
        throws ArchivaRestServiceException {
    log.debug("Deleting file {}", fileName);
    // we make sure, that there are no other path components in the filename:
    String checkedFileName = Paths.get(fileName).getFileName().toString();
    Path file = SystemUtils.getJavaIoTmpDir().toPath().resolve(checkedFileName);
    log.debug("delete file:{},exists:{}", file, Files.exists(file));
    boolean removed = getSessionFileMetadatas().remove(new FileMetadata(fileName));
    // try with full name as ui only know the file name
    if (!removed) {
        removed = getSessionFileMetadatas().remove(new FileMetadata(file.toString()));
    }
    if (removed) {
        try {
            Files.deleteIfExists(file);
            return Boolean.TRUE;
        } catch (IOException e) {
            log.error("Could not delete file {}: {}", file, e.getMessage(), e);
        }
    }
    return Boolean.FALSE;
}
 
Example #12
Source File: ProcessUtil.java    From elasticsearch-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Build an OS dependent command line to kill the process with the given PID.
 * @param pid The ID of the process to kill
 * @return the command line required to kill the given process
 */
public static CommandLine buildKillCommandLine(String pid)
{
    CommandLine command;

    if (SystemUtils.IS_OS_WINDOWS)
    {
        command = new CommandLine("taskkill")
                .addArgument("/F")
                .addArgument("/pid")
                .addArgument(pid);
    }
    else
    {
        command = new CommandLine("kill").addArgument(pid);
    }
    
    return command;
}
 
Example #13
Source File: CheckGcpEnvironment.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static boolean isRunningOnGcp() {
  try {
    if (SystemUtils.IS_OS_LINUX) {
      // Checks GCE residency on Linux platform.
      return checkProductNameOnLinux(Files.newBufferedReader(Paths.get(DMI_PRODUCT_NAME), UTF_8));
    } else if (SystemUtils.IS_OS_WINDOWS) {
      // Checks GCE residency on Windows platform.
      Process p =
          new ProcessBuilder()
              .command(WINDOWS_COMMAND, "Get-WmiObject", "-Class", "Win32_BIOS")
              .start();
      return checkBiosDataOnWindows(
          new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8)));
    }
  } catch (IOException e) {
    logger.log(Level.WARNING, "Fail to read platform information: ", e);
    return false;
  }
  // Platforms other than Linux and Windows are not supported.
  return false;
}
 
Example #14
Source File: CheckGcpEnvironment.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static boolean isRunningOnGcp() {
  try {
    if (SystemUtils.IS_OS_LINUX) {
      // Checks GCE residency on Linux platform.
      return checkProductNameOnLinux(Files.newBufferedReader(Paths.get(DMI_PRODUCT_NAME), UTF_8));
    } else if (SystemUtils.IS_OS_WINDOWS) {
      // Checks GCE residency on Windows platform.
      Process p =
          new ProcessBuilder()
              .command(WINDOWS_COMMAND, "Get-WmiObject", "-Class", "Win32_BIOS")
              .start();
      return checkBiosDataOnWindows(
          new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8)));
    }
  } catch (IOException e) {
    logger.log(Level.WARNING, "Fail to read platform information: ", e);
    return false;
  }
  // Platforms other than Linux and Windows are not supported.
  return false;
}
 
Example #15
Source File: LocalResourceIdTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveInWindowsOS() {
  if (!SystemUtils.IS_OS_WINDOWS) {
    // Skip tests
    return;
  }
  assertEquals(
      toResourceIdentifier("C:\\my home\\out put"),
      toResourceIdentifier("C:\\my home\\")
          .resolve("out put", StandardResolveOptions.RESOLVE_FILE));

  assertEquals(
      toResourceIdentifier("C:\\out put"),
      toResourceIdentifier("C:\\my home\\")
          .resolve("..", StandardResolveOptions.RESOLVE_DIRECTORY)
          .resolve(".", StandardResolveOptions.RESOLVE_DIRECTORY)
          .resolve("out put", StandardResolveOptions.RESOLVE_FILE));

  assertEquals(
      toResourceIdentifier("C:\\my home\\**\\*"),
      toResourceIdentifier("C:\\my home\\")
          .resolve("**", StandardResolveOptions.RESOLVE_DIRECTORY)
          .resolve("*", StandardResolveOptions.RESOLVE_FILE));
}
 
Example #16
Source File: StringUtils.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
public static void startupShutdownMessage(VersionInfo versionInfo,
    Class<?> clazz, String[] args, Logger log) {
  final String hostname = NetUtils.getHostname();
  final String className = clazz.getSimpleName();
  if (log.isInfoEnabled()) {
    log.info(createStartupShutdownMessage(versionInfo, className, hostname,
        args));
  }

  if (SystemUtils.IS_OS_UNIX) {
    try {
      SignalLogger.INSTANCE.register(log);
    } catch (Throwable t) {
      log.warn("failed to register any UNIX signal loggers: ", t);
    }
  }
  ShutdownHookManager.get().addShutdownHook(
      () -> log.info(toStartupShutdownString("SHUTDOWN_MSG: ",
          "Shutting down " + className + " at " + hostname)),
      SHUTDOWN_HOOK_PRIORITY);

}
 
Example #17
Source File: MultiLineToStringStyleTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testObject() {
    final Integer i3 = Integer.valueOf(3);
    final Integer i4 = Integer.valueOf(4);
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  <null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) null).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(i3).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) null).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=3" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=3" + SystemUtils.LINE_SEPARATOR + "  b=4" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<Integer>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", i3, false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<size=0>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=[]" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new ArrayList<Object>(), true).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<size=0>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a={}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", new HashMap<Object, Object>(), true).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a=<size=0>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  a={}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
}
 
Example #18
Source File: PCGenDataConvert.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void main(String[] args)
{
	Logging.log(Level.INFO, "Starting PCGen Data Converter v" + PCGenPropBundle.getVersionNumber()); //$NON-NLS-1$
	configFactory = new PropertyContextFactory(SystemUtils.USER_DIR);
	configFactory.registerAndLoadPropertyContext(ConfigurationSettings.getInstance());
	Main.loadProperties(true);
	getConverter().setVisible(true);
}
 
Example #19
Source File: EarthApp.java    From collect-earth with MIT License 5 votes vote down vote up
/**
 * Start the application, opening Google Earth and starting the Jetty server.
 * 
 * @param args
 *            No arguments are used by this method.
 */
public static void main(String[] args) {

	try {

		// System property used in the web.xml configuration
		System.setProperty("collectEarth.userFolder", FolderFinder.getCollectEarthDataFolder()); //$NON-NLS-1$

		initializeSentry();

		// Change of font so that Lao and Thao glyphs are supported
		CollectEarthUtils.setFontDependingOnLanguaue( getLocalProperties().getUiLanguage() );

		logger = LoggerFactory.getLogger(EarthApp.class);

		String doubleClickedProjectFile = null;

		if (args != null && args.length == 1) {
			doubleClickedProjectFile = args[0];
		}else if( getProjectsService().getProjectList().size() == 0 ){
			doubleClickedProjectFile = "resources/demo_survey.cep";
		}

		if ( SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX){
			handleMacStartup( doubleClickedProjectFile );
		}else{
			startCollectEarth( doubleClickedProjectFile );
		}

	} catch (final Exception e) {
		// The logger factory has not been initialized, this will not work, just output to console
		if (logger != null) {
			logger.error("The server could not start", e); //$NON-NLS-1$
		}
		e.printStackTrace();
		System.exit(1);
	} finally {
		closeSplash();
	}
}
 
Example #20
Source File: Terminal.java    From TerminalFX with MIT License 5 votes vote down vote up
private void initializeProcess() throws Exception {
    final Path dataDir = getDataDir();
    if (SystemUtils.IS_OS_WINDOWS) {
        this.termCommand = getTerminalConfig().getWindowsTerminalStarter().split("\\s+");
    } else {
        this.termCommand = getTerminalConfig().getUnixTerminalStarter().split("\\s+");
    }

    final Map<String, String> envs = new HashMap<>(System.getenv());
    envs.put("TERM", "xterm");

    System.setProperty("PTY_LIB_FOLDER", dataDir.resolve("libpty").toString());

    if (Objects.nonNull(terminalPath) && Files.exists(terminalPath)) {
        this.process = PtyProcess.exec(termCommand, envs, terminalPath.toString());
    } else {
        this.process = PtyProcess.exec(termCommand, envs);
    }

    columnsProperty().addListener(evt -> updateWinSize());
    rowsProperty().addListener(evt -> updateWinSize());
    updateWinSize();
    setInputReader(new BufferedReader(new InputStreamReader(process.getInputStream())));
    setErrorReader(new BufferedReader(new InputStreamReader(process.getErrorStream())));
    setOutputWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())));
    focusCursor();

    countDownLatch.countDown();

    process.waitFor();
}
 
Example #21
Source File: TestServerAndClient.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonPersistentSetServerAndClient() throws InitializationException, IOException {

    /**
     * This bypasses the test for build environments in OS X running Java 1.8 due to a JVM bug
     * See:  https://issues.apache.org/jira/browse/NIFI-437
     */
    Assume.assumeFalse("test is skipped due to build environment being OS X with JDK 1.8. See https://issues.apache.org/jira/browse/NIFI-437",
        SystemUtils.IS_OS_MAC && SystemUtils.IS_JAVA_1_8);

    LOGGER.info("Testing " + Thread.currentThread().getStackTrace()[1].getMethodName());
    // Create server
    final TestRunner runner = TestRunners.newTestRunner(Mockito.mock(Processor.class));
    final DistributedSetCacheServer server = new SetServer();
    runner.addControllerService("server", server);
    runner.enableControllerService(server);

    final DistributedSetCacheClientService client = createClient(server.getPort());
    final Serializer<String> serializer = new StringSerializer();
    final boolean added = client.addIfAbsent("test", serializer);
    assertTrue(added);

    final boolean contains = client.contains("test", serializer);
    assertTrue(contains);

    final boolean addedAgain = client.addIfAbsent("test", serializer);
    assertFalse(addedAgain);

    final boolean removed = client.remove("test", serializer);
    assertTrue(removed);

    final boolean containedAfterRemove = client.contains("test", serializer);
    assertFalse(containedAfterRemove);

    server.shutdownServer();
}
 
Example #22
Source File: JdkGenericDumpTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
private static Set<String> findJavaHomes() {
    if (SystemUtils.IS_OS_WINDOWS) {
        return findJavaHomesOnWindows();
    }
    final Set<String> javaHomes = new HashSet<>(1);
    javaHomes.add(SystemUtils.JAVA_HOME);
    return javaHomes;
}
 
Example #23
Source File: NativeBundle.java    From spoofax with Apache License 2.0 5 votes vote down vote up
/**
 * @return Name of the sdf2table executable, relative to the directory returned from {@link #getNativeDirectory()}.
 */
public static String getSdf2TableName() {
    if(SystemUtils.IS_OS_WINDOWS) {
        return "sdf2table.exe";
    } else {
        return "sdf2table";
    }
}
 
Example #24
Source File: BuildCLI.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
protected void inferOS(){
    if(SystemUtils.IS_OS_LINUX) {
        os = Collections.singletonList(OS.LINUX.name());
    } else if(SystemUtils.IS_OS_WINDOWS){
        os = Collections.singletonList(OS.WINDOWS.name());
    } else  if(SystemUtils.IS_OS_MAC){
        os = Collections.singletonList(OS.MACOSX.name());
    } else {
        throw new IllegalStateException("No OS was provided and operating system could not be inferred");
    }
}
 
Example #25
Source File: TestServerAndClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testNonPersistentSetServerAndClient() throws InitializationException, IOException {
    /**
     * This bypasses the test for build environments in OS X running Java 1.8 due to a JVM bug
     * See:  https://issues.apache.org/jira/browse/NIFI-437
     */
    Assume.assumeFalse("test is skipped due to build environment being OS X with JDK 1.8. See https://issues.apache.org/jira/browse/NIFI-437",
            SystemUtils.IS_OS_MAC && SystemUtils.IS_JAVA_1_8);

    LOGGER.info("Testing " + Thread.currentThread().getStackTrace()[1].getMethodName());
    // Create server
    final TestRunner runner = TestRunners.newTestRunner(Mockito.mock(Processor.class));
    final DistributedSetCacheServer server = new SetServer();
    runner.addControllerService("server", server);
    runner.enableControllerService(server);

    final DistributedSetCacheClientService client = createClient(server.getPort());
    final Serializer<String> serializer = new StringSerializer();
    final boolean added = client.addIfAbsent("test", serializer);
    assertTrue(added);

    final boolean contains = client.contains("test", serializer);
    assertTrue(contains);

    final boolean addedAgain = client.addIfAbsent("test", serializer);
    assertFalse(addedAgain);

    final boolean removed = client.remove("test", serializer);
    assertTrue(removed);

    final boolean containedAfterRemove = client.contains("test", serializer);
    assertFalse(containedAfterRemove);

    server.shutdownServer();
}
 
Example #26
Source File: SybaseIqAppContext.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public CsvStaticDataDeployer getCsvStaticDataLoader() {
    if (getIqDataSource().isIqClientLoadSupported()) {
        LOG.info("Using IQ Client load mechanism for IQ CSV Loads");
        IqLoadMode iqLoadMode = SystemUtils.IS_OS_WINDOWS ? IqLoadMode.IQ_CLIENT_WINDOWS : IqLoadMode.IQ_CLIENT;
        File workDir = Optional.ofNullable(this.getWorkDir())
                .orElseGet(() -> FileUtilsCobra.createTempDir(SystemUtils.USER_NAME + "-obevo"));
        return new IqBulkLoadCsvStaticDataDeployer(this.env, this.getSqlExecutor(), this.getIqDataSource(),
                this.getDbMetadataManager(), this.env.getPlatform(), iqLoadMode, workDir);
    } else {
        LOG.info("Using the default SQL insert/update/delete statements for IQ CSV Loads");
        return super.getCsvStaticDataLoader();
    }
}
 
Example #27
Source File: LoggingBootstrap.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes all Logging for HiveMQ. Call this method only once
 * at the very beginning of the HiveMQ lifecycle
 */
public static void initLogging(final @NotNull File configFolder) {

    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    final ch.qos.logback.classic.Logger logger = getRootLogger();

    context.addListener(new LogbackChangeListener(logger));

    final boolean overridden = overrideLogbackXml(configFolder);

    if (!overridden) {
        reEnableDefaultAppenders();
    }
    redirectJULToSLF4J();
    logQueuedEntries();

    reset();

    // must be added here, as addLoglevelModifiers() is much to late
    if (SystemUtils.IS_OS_WINDOWS) {
        context.addTurboFilter(xodusFileDataWriterLogLevelModificator);
        log.trace("Added Xodus log level modifier for FileDataWriter.class");
    }

    context.addTurboFilter(nettyLogLevelModifier);
    log.trace("Added Netty log level modifier");
}
 
Example #28
Source File: PlatformUtil.java    From milkman with MIT License 5 votes vote down vote up
private static String getOsSpecificAppDataFolder(String filename) {
	if (SystemUtils.IS_OS_WINDOWS) {
		return Paths.get(System.getenv("LOCALAPPDATA"), "Milkman", filename).toString();
	} else if (SystemUtils.IS_OS_MAC) {
		return Paths.get(System.getProperty("user.home"), "Library", "Application Support", "Milkman", filename).toString();
	} else if (SystemUtils.IS_OS_LINUX) {
		return Paths.get(System.getProperty("user.home"), ".milkman", filename).toString();
	}
	
	return filename;
	
}
 
Example #29
Source File: DataLoadTest.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void loadGameModes()
{
	String pccLoc = TestHelper.findDataFolder();
	System.out.println("Got data folder of " + pccLoc);
	try
	{
		String configFolder = "testsuite";
		TestHelper.createDummySettingsFile(TEST_CONFIG_FILE, configFolder,
			pccLoc);
	}
	catch (IOException e)
	{
		Logging.errorPrint("DataTest.loadGameModes failed", e);
	}

	PropertyContextFactory configFactory =
			new PropertyContextFactory(SystemUtils.USER_DIR);
	configFactory.registerAndLoadPropertyContext(ConfigurationSettings
		.getInstance(TEST_CONFIG_FILE));
	Main.loadProperties(false);
	PCGenTask loadPluginTask = Main.createLoadPluginTask();
	loadPluginTask.run();
	PCGenTask gameModeFileLoader = new GameModeFileLoader();
	gameModeFileLoader.run();
	PCGenTask campaignFileLoader = new CampaignFileLoader();
	campaignFileLoader.run();
}
 
Example #30
Source File: PCGenSettings.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static String unexpandRelativePath(String path)
{
	if (path.startsWith(SystemUtils.USER_DIR + File.separator))
	{
		path = '@' + path.substring(SystemUtils.USER_DIR.length() + 1);
	}
	return path;
}