org.apache.commons.lang.SystemUtils Java Examples

The following examples show how to use org.apache.commons.lang.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: TestEnhancedByteBufferAccess.java    From big-c with Apache License 2.0 6 votes vote down vote up
public static HdfsConfiguration initZeroCopyTest() {
  Assume.assumeTrue(NativeIO.isAvailable());
  Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
  HdfsConfiguration conf = new HdfsConfiguration();
  conf.setBoolean(DFSConfigKeys.DFS_CLIENT_READ_SHORTCIRCUIT_KEY, true);
  conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, BLOCK_SIZE);
  conf.setInt(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_SIZE, 3);
  conf.setLong(DFSConfigKeys.DFS_CLIENT_MMAP_CACHE_TIMEOUT_MS, 100);
  conf.set(DFSConfigKeys.DFS_DOMAIN_SOCKET_PATH_KEY,
      new File(sockDir.getDir(),
        "TestRequestMmapAccess._PORT.sock").getAbsolutePath());
  conf.setBoolean(DFSConfigKeys.
      DFS_CLIENT_READ_SHORTCIRCUIT_SKIP_CHECKSUM_KEY, true);
  conf.setLong(DFS_HEARTBEAT_INTERVAL_KEY, 1);
  conf.setLong(DFS_CACHEREPORT_INTERVAL_MSEC_KEY, 1000);
  conf.setLong(DFS_NAMENODE_PATH_BASED_CACHE_REFRESH_INTERVAL_MS, 1000);
  return conf;
}
 
Example #2
Source File: CLIProcessManager.java    From IGUANA with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Process createProcess(String command) {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.redirectErrorStream(true);

    Process process = null;
    try {
        if (SystemUtils.IS_OS_LINUX) {

            processBuilder.command("bash", "-c", command);

        } else if (SystemUtils.IS_OS_WINDOWS) {
            processBuilder.command("cmd.exe", "-c", command);
        }
        process = processBuilder.start();

    } catch (IOException e) {
        System.out.println("New process could not be created: " + e.getLocalizedMessage());
    }

    return process;
}
 
Example #3
Source File: ExternalPythonExecutor.java    From score with Apache License 2.0 6 votes vote down vote up
private void addFilePermissions(File file) throws IOException {
    Set<PosixFilePermission> filePermissions = new HashSet<>();
    filePermissions.add(PosixFilePermission.OWNER_READ);

    File[] fileChildren = file.listFiles();

    if (fileChildren != null) {
        for (File child : fileChildren) {
            if (SystemUtils.IS_OS_WINDOWS) {
                child.setReadOnly();
            } else {
                Files.setPosixFilePermissions(child.toPath(), filePermissions);
            }
        }
    }
}
 
Example #4
Source File: AtoumUtils.java    From phpstorm-plugin with MIT License 6 votes vote down vote up
public static String findAtoumBinPath(VirtualFile dir)
{
    String defaultBinPath = dir.getPath() + "/vendor/bin/atoum";
    String atoumBinPath = defaultBinPath;

    String binDir = getComposerBinDir(dir.getPath() + "/composer.json");
    String binPath = dir.getPath() + "/" + binDir + "/atoum";
    if (null != binDir && new File(binPath).exists()) {
        atoumBinPath = binPath;
    }

    if (SystemUtils.IS_OS_WINDOWS) {
        atoumBinPath += ".bat";
    }

    return atoumBinPath;
}
 
Example #5
Source File: AccumuloInstanceDriver.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Copies the HADOOP_HOME bin directory to the {@link MiniAccumuloCluster} temp directory.
 * {@link MiniAccumuloCluster} expects to find bin/winutils.exe in the MAC temp
 * directory instead of HADOOP_HOME for some reason.
 * @throws IOException
 */
private void copyHadoopHomeToTemp() throws IOException {
    if (IS_COPY_HADOOP_HOME_ENABLED && SystemUtils.IS_OS_WINDOWS) {
        final String hadoopHomeEnv = PathUtils.clean(System.getenv("HADOOP_HOME"));
        if (hadoopHomeEnv != null) {
            final File hadoopHomeDir = new File(hadoopHomeEnv);
            if (hadoopHomeDir.exists()) {
                final File binDir = Paths.get(hadoopHomeDir.getAbsolutePath(), "/bin").toFile();
                if (binDir.exists()) {
                    FileUtils.copyDirectoryToDirectory(binDir, tempDir);
                } else {
                    log.warn("The specified path for the Hadoop bin directory does not exist: " + binDir.getAbsolutePath());
                }
            } else {
                log.warn("The specified path for HADOOP_HOME does not exist: " + hadoopHomeDir.getAbsolutePath());
            }
        } else {
            log.warn("The HADOOP_HOME environment variable was not found.");
        }
    }
}
 
Example #6
Source File: ScriptTest.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Test
public void executeWithOutputInterpreter() {
    Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
    Script script = new Script("/bin/bash");
    script.add("-c");
    script.add("echo 'hello world!'");
    String value = script.execute(new OutputInterpreter() {

        @Override
        public String interpret(BufferedReader reader) throws IOException {
            throw new IllegalArgumentException();
        }
    });
    // it is a stack trace in this case as string
    Assert.assertNotNull(value);
}
 
Example #7
Source File: ScriptTest.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Test
public void executeWithOutputInterpreter() {
    Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
    final Script script = new Script("/bin/bash");
    script.add("-c");
    script.add("echo 'hello world!'");
    final String value = script.execute(new OutputInterpreter() {

        @Override
        public String interpret(final BufferedReader reader) throws IOException {
            throw new IllegalArgumentException();
        }
    });
    // it is a stack trace in this case as string
    Assert.assertNotNull(value);
}
 
Example #8
Source File: JarManagerService.java    From DBus with Apache License 2.0 6 votes vote down vote up
public ResultEntity uploads(String category, String version, String type, MultipartFile jarFile) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    headers.setContentDispositionFormData("jarFile", jarFile.getOriginalFilename());

    MultiValueMap<String, Object> data = new LinkedMultiValueMap<>();
    File saveDir = new File(SystemUtils.getJavaIoTmpDir(), String.valueOf(System.currentTimeMillis()));
    if (!saveDir.exists()) saveDir.mkdirs();
    File tempFile = new File(saveDir, jarFile.getOriginalFilename());
    jarFile.transferTo(tempFile);
    FileSystemResource fsr = new FileSystemResource(tempFile);
    data.add("jarFile", fsr);

    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(data, headers);
    URLBuilder urlBulider = new URLBuilder(ServiceNames.KEEPER_SERVICE, "/jars/uploads/{0}/{1}/{2}");
    ResponseEntity<ResultEntity> result = rest.postForEntity(urlBulider.build(), entity, ResultEntity.class, version, type, category);
    if (tempFile.exists()) tempFile.delete();
    if (saveDir.exists()) saveDir.delete();

    return result.getBody();
}
 
Example #9
Source File: ProjectTopologyService.java    From DBus with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        String line = br.readLine();
        while (StringUtils.isNotBlank(line)) {
            if (session != null)
                session.getBasicRemote().sendText(line);
            if (smt != null)
                smt.convertAndSendToUser(uid, "/log", line);
            sb.append(line);
            sb.append(SystemUtils.LINE_SEPARATOR);
            line = br.readLine();
        }
    } catch (Exception e) {
        logger.error("stream runnable error", e);
    } finally {
        close(br);
        close(reader);
    }
}
 
Example #10
Source File: ExceptionUtils.java    From lams 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 getStackFrameList(Throwable t) {
    String stackTrace = getStackTrace(t);
    String linebreak = SystemUtils.LINE_SEPARATOR;
    StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
    List list = new ArrayList();
    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: FixedResultSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
/**
 * checks for correct configuration, and translates the fileName to
 * a file, to check existence. 
 * If a fileName was specified, the contents of the file is put in the
 * <code>returnString</code>, so that allways the <code>returnString</code>
 * may be returned.
 * @throws ConfigurationException
 */
@Override
public void configure() throws ConfigurationException {
	super.configure();
    
	if (StringUtils.isNotEmpty(fileName)) {
		try {
			returnString = Misc.resourceToString(ClassUtils.getResourceURL(getConfigurationClassLoader(), fileName), SystemUtils.LINE_SEPARATOR);
		} catch (Throwable e) {
			throw new ConfigurationException("Pipe [" + getName() + "] got exception loading ["+fileName+"]", e);
		}
	}
	if ((StringUtils.isEmpty(fileName)) && returnString==null) {  // allow an empty returnString to be specified
		throw new ConfigurationException("Pipe [" + getName() + "] has neither fileName nor returnString specified");
	}
	if (StringUtils.isNotEmpty(replaceFrom)) {
		returnString = replace(returnString, replaceFrom, replaceTo );
	}
}
 
Example #12
Source File: DialectFactory.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
public static synchronized DialectFactory getInstance() {
    if (me == null) {
        me = new DialectFactory();
        me.registerDialect(new DB2Dialect());
        me.registerDialect(new MSSQLDialect());
        me.registerDialect(new MySQLDialect());
        me.registerDialect(new MySQLInnoDBDialect());
        me.registerDialect(new OracleDialect());
        me.registerDialect(new PostgresDialect());
        me.registerDialect(new H2Dialect());
        me.registerDialect(new HSQLDBDialect());

        // provide MSAccessDialect only on Windows-Systems due to the
        // requirement of the JET/ACE-Engine
        if (SystemUtils.IS_OS_WINDOWS) {
            me.registerDialect(new MSAccessDialect());
        }
    }

    return me;
}
 
Example #13
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 6 votes vote down vote up
private void commitFile(String dirName, String fileName, boolean longpathsEnabled) throws Exception {
    assertTrue("Didn't mkdir " + dirName, w.file(dirName).mkdir());

    String fullName = dirName + File.separator + fileName;
    w.touch(fullName, fullName + " content " + UUID.randomUUID().toString());

    boolean shouldThrow = !longpathsEnabled &&
        SystemUtils.IS_OS_WINDOWS &&
        w.git instanceof CliGitAPIImpl &&
        w.cgit().isAtLeastVersion(1, 9, 0, 0) &&
        !w.cgit().isAtLeastVersion(2, 8, 0, 0) &&
        (new File(fullName)).getAbsolutePath().length() > MAX_PATH;

    try {
        w.git.add(fullName);
        w.git.commit("commit-" + fileName);
        assertFalse("unexpected success " + fullName, shouldThrow);
    } catch (GitException ge) {
        assertEquals("Wrong message", "Cannot add " + fullName, ge.getMessage());
    }
    assertTrue("file " + fullName + " missing at commit", w.file(fullName).exists());
}
 
Example #14
Source File: MountableFile.java    From testcontainers-java with MIT License 6 votes vote down vote up
@UnstableAPI
public static int getUnixFileMode(final Path path) {
    try {
        int unixMode = (int) Files.readAttributes(path, "unix:mode").get("mode");
        // Truncate mode bits for z/OS
        if ("OS/390".equals(SystemUtils.OS_NAME) ||
            "z/OS".equals(SystemUtils.OS_NAME) ||
            "zOS".equals(SystemUtils.OS_NAME) ) {
            unixMode &= TarConstants.MAXID;
            unixMode |= Files.isDirectory(path) ? 040000 : 0100000;
        }
        return unixMode;
    } catch (IOException | UnsupportedOperationException e) {
        // fallback for non-posix environments
        int mode = DEFAULT_FILE_MODE;
        if (Files.isDirectory(path)) {
            mode = DEFAULT_DIR_MODE;
        } else if (Files.isExecutable(path)) {
            mode |= 0111; // equiv to +x for user/group/others
        }

        return mode;
    }
}
 
Example #15
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 getStackFrameList(Throwable t) {
    String stackTrace = getStackTrace(t);
    String linebreak = SystemUtils.LINE_SEPARATOR;
    StringTokenizer frames = new StringTokenizer(stackTrace, linebreak);
    List list = new ArrayList();
    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 #16
Source File: ScmRenderer.java    From maven-confluence-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Create the documentation to provide an developer access with a
 * <code>Perforce</code> SCM. For example, generate the following command
 * line:
 * <p>
 * p4 -H hostname -p port -u username -P password path
 * </p>
 * <p>
 * p4 -H hostname -p port -u username -P password path submit -c changement
 * </p>
 *
 * @param perforceRepo
 * @see <a
 *      href="http://www.perforce.com/perforce/doc.051/manuals/cmdref/index.html">http://www.perforce.com/
 * perforce /doc.051/manuals/cmdref/index.html</>
 */
// CHECKSTYLE_ON: LineLength
private void developerAccessPerforce(PerforceScmProviderRepository perforceRepo) {
    paragraph(getI18nString("devaccess.perforce.intro"));

    StringBuilder command = new StringBuilder();
    command.append("$ p4");
    if (!StringUtils.isEmpty(perforceRepo.getHost())) {
        command.append(" -H ").append(perforceRepo.getHost());
    }
    if (perforceRepo.getPort() > 0) {
        command.append(" -p ").append(perforceRepo.getPort());
    }
    command.append(" -u username");
    command.append(" -P password");
    command.append(" ");
    command.append(perforceRepo.getPath());
    command.append(SystemUtils.LINE_SEPARATOR);
    command.append("$ p4 submit -c \"A comment\"");

    verbatimText(command.toString());
}
 
Example #17
Source File: RuleCompatibleHelperTest.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCompatible_le() {
    try {
        Resource resource = new PathMatchingResourcePatternResolver().getResource("classpath:compatible/le-spring-context.xml");
        String ruleStr = StringUtils.join(IOUtils.readLines(resource.getInputStream()), SystemUtils.LINE_SEPARATOR);
        ApplicationContext context = new StringXmlApplicationContext(RuleCompatibleHelper.compatibleRule(ruleStr));
        VirtualTableRoot vtr1 = (VirtualTableRoot) context.getBean("vtabroot");
        Assert.assertNotNull(vtr1);
    } catch (IOException e) {
        Assert.fail(ExceptionUtils.getFullStackTrace(e));
    }
}
 
Example #18
Source File: TestSignalLogger.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test(timeout=60000)
public void testInstall() throws Exception {
  Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
  SignalLogger.INSTANCE.register(LOG);
  try {
    SignalLogger.INSTANCE.register(LOG);
    Assert.fail("expected IllegalStateException from double registration");
  } catch (IllegalStateException e) {
    // fall through
  }
}
 
Example #19
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-21168")
private void checkSymlinkSetting(WorkingArea area) throws IOException {
    String expected = SystemUtils.IS_OS_WINDOWS ? "false" : "";
    String symlinkValue;
    try {
        symlinkValue = w.launchCommand(true, "git", "config", "core.symlinks").trim();
    } catch (Exception e) {
        symlinkValue = e.getMessage();
    }
    assertEquals(expected, symlinkValue);
}
 
Example #20
Source File: ToStringStyle.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Constructor.</p>
 *
 * <p>Use the static constant rather than instantiating.</p>
 */
MultiLineToStringStyle() {
    super();
    this.setContentStart("[");
    this.setFieldSeparator(SystemUtils.LINE_SEPARATOR + "  ");
    this.setFieldSeparatorAtStart(true);
    this.setContentEnd(SystemUtils.LINE_SEPARATOR + "]");
}
 
Example #21
Source File: LibvirtComputingResourceTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetNicStats() {
    // this test is only working on linux because of the loopback interface name
    // also the tested code seems to work only on linux
    Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
    final LibvirtComputingResource libvirtComputingResource = new LibvirtComputingResource();
    final Pair<Double, Double> stats = libvirtComputingResource.getNicStats("lo");
    assertNotNull(stats);
}
 
Example #22
Source File: MultiLineToStringStyleTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testLongArrayArray() {
    long[][] array = new long[][] {{1, 2}, null, {5}};
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  {{1,2},<null>,{5}}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  {{1,2},<null>,{5}}" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString());
    array = null;
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  <null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append(array).toString());
    assertEquals(baseStr + "[" + SystemUtils.LINE_SEPARATOR + "  <null>" + SystemUtils.LINE_SEPARATOR + "]", new ToStringBuilder(base).append((Object) array).toString());
}
 
Example #23
Source File: AbstractTerminalCommand.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Override
public ProcessBuilder getShell() {
    validateWorkingDirectory(workingDirectory);

    List<String> commands = new ArrayList<>();
    if (SystemUtils.IS_OS_UNIX) {
        commands.add(BASH);
    } else {
        commands.add(CMD);
    }

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.directory(workingDirectory);
    return pb;
}
 
Example #24
Source File: ProcessUtilTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Test
public void pidCheck() throws ConfigurationException, IOException {
    Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
    FileUtils.writeStringToFile(pidFile, "123456\n");
    ProcessUtil.pidCheck(pidFile.getParent(), pidFile.getName());
    final String pidStr = FileUtils.readFileToString(pidFile);
    Assert.assertFalse("pid can not be blank", pidStr.isEmpty());
    final int pid = Integer.parseInt(pidStr.trim());
    final int maxPid = Integer.parseInt(FileUtils.readFileToString(new File("/proc/sys/kernel/pid_max")).trim());
    Assert.assertTrue(pid <= maxPid);
}
 
Example #25
Source File: StrBuilderAppendInsertTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testAppendNewLine() {
    StrBuilder sb = new StrBuilder("---");
    sb.appendNewLine().append("+++");
    assertEquals("---" + SystemUtils.LINE_SEPARATOR + "+++", sb.toString());
    
    sb = new StrBuilder("---");
    sb.setNewLineText("#").appendNewLine().setNewLineText(null).appendNewLine();
    assertEquals("---#" + SystemUtils.LINE_SEPARATOR, sb.toString());
}
 
Example #26
Source File: SimpleMariaDBTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void testMariaDBWithCustomIniFile() throws SQLException {
    assumeFalse(SystemUtils.IS_OS_WINDOWS);

    try (MariaDBContainer<?> mariadbCustomConfig = new MariaDBContainer<>("mariadb:10.1.16")
        .withConfigurationOverride("somepath/mariadb_conf_override")) {
        mariadbCustomConfig.start();

        ResultSet resultSet = performQuery(mariadbCustomConfig, "SELECT @@GLOBAL.innodb_file_format");
        String result = resultSet.getString(1);

        assertEquals("The InnoDB file format has been set by the ini file content", "Barracuda", result);
    }
}
 
Example #27
Source File: ScriptTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Test
public void testEcho() {
    Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
    final Script script = new Script("/bin/echo");
    script.add("bar");
    final OutputInterpreter.AllLinesParser resultParser = new OutputInterpreter.AllLinesParser();
    final String result = script.execute(resultParser);
    // With allLinesParser, result is not comming from the return value
    Assert.assertNull(result);
    Assert.assertEquals("bar\n", resultParser.getLines());
}
 
Example #28
Source File: MMapURITest.java    From netbeans-mmd-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsURI_Linux_CreatedAsFile() throws Exception {
  if (SystemUtils.IS_OS_LINUX) {
    final Properties props = new Properties();
    props.put("Kõik või", "tere");

    final MMapURI uri = new MMapURI(null, new File("/Kõik/või/mitte/midagi.txt"), props);
    assertEquals(new URI("file:///K%C3%B5ik/v%C3%B5i/mitte/midagi.txt?K%C3%B5ik+v%C3%B5i=tere"), uri.asURI());
    assertEquals("tere", uri.getParameters().getProperty("Kõik või"));
    assertEquals(new File("/Kõik/või/mitte/midagi.txt"), uri.asFile(null));
  }
}
 
Example #29
Source File: ScriptTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogger() {
    Assume.assumeTrue(SystemUtils.IS_OS_LINUX);
    Logger mock = Mockito.mock(Logger.class);
    Mockito.doNothing().when(mock).debug(Matchers.any());
    Script script = new Script("/bin/echo", mock);
    script.execute();
}
 
Example #30
Source File: CommonsUtils.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param url
 * @return
 * @throws IOException
 */
public static String get(String url) throws IOException {
	Request request = new Request.Builder()
			.url(url)
			.header("user-agent",  String.format("RB/%s (%s/%s)", Application.VER, SystemUtils.OS_NAME, SystemUtils.JAVA_SPECIFICATION_VERSION))
			.build();

	try (Response response = getHttpClient().newCall(request).execute()) {
		return Objects.requireNonNull(response.body()).string();
	}
}