Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/io/File/GetXSpace.java
38812 views
/*1* Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 4057701 6286712 636437726* @ignore until 6492634 and 6501010 is fixed27* @run build GetXSpace28* @run shell GetXSpace.sh29* @summary Basic functionality of File.get-X-Space methods.30* @key randomness31*/3233import java.io.BufferedReader;34import java.io.File;35import java.io.FilePermission;36import java.io.InputStreamReader;37import java.io.IOException;38import java.security.Permission;39import java.util.ArrayList;40import java.util.regex.Matcher;41import java.util.regex.Pattern;4243import static java.lang.System.out;4445public class GetXSpace {4647private static SecurityManager [] sma = { null, new Allow(), new DenyFSA(),48new DenyRead() };4950private static final String name = System.getProperty("os.name");51private static final String dfFormat;52static {53if (name.equals("SunOS") || name.equals("Linux")54|| name.contains("OS X")) {55// FileSystem Total Used Available Use% MountedOn56dfFormat = "([^\\s]+)\\s+(\\d+)\\s+\\d+\\s+(\\d+)\\s+\\d+%\\s+([^\\s]+)";57} else if (name.startsWith("Windows")) {58// Drive (MountedOn) Available/Total59dfFormat = "([^\\s]+)\\s+\\(([^\\s]+)\\)\\s+(\\d+)\\/(\\d+)\\s+";60} else {61throw new RuntimeException("unrecognized system:"62+ " os.name == " + name);63}64}65private static Pattern dfPattern = Pattern.compile(dfFormat);6667private static int fail = 0;68private static int pass = 0;69private static Throwable first;7071static void pass() {72pass++;73}7475static void fail(String p) {76if (first == null)77setFirst(p);78System.err.format("FAILED: %s%n", p);79fail++;80}8182static void fail(String p, long exp, String cmp, long got) {83String s = String.format("'%s': %d %s %d", p, exp, cmp, got);84if (first == null)85setFirst(s);86System.err.format("FAILED: %s%n", s);87fail++;88}8990private static void fail(String p, Class ex) {91String s = String.format("'%s': expected %s - FAILED%n", p, ex.getName());92if (first == null)93setFirst(s);94System.err.format("FAILED: %s%n", s);95fail++;96}9798private static void setFirst(String s) {99try {100throw new RuntimeException(s);101} catch (RuntimeException x) {102first = x;103}104}105106private static class Space {107private static final long KSIZE = 1024;108private String name;109private long total;110private long free;111112Space(String total, String free, String name) {113try {114this.total = Long.valueOf(total) * KSIZE;115this.free = Long.valueOf(free) * KSIZE;116} catch (NumberFormatException x) {117// the regex should have caught this118assert false;119}120this.name = name;121}122123String name() { return name; }124long total() { return total; }125long free() { return free; }126boolean woomFree(long freeSpace) {127return ((freeSpace >= (free / 10)) && (freeSpace <= (free * 10)));128}129public String toString() {130return String.format("%s (%d/%d)", name, free, total);131}132}133134private static ArrayList space(String f) throws IOException {135ArrayList al = new ArrayList();136137Process p = null;138String cmd = "df -k" + (f == null ? "" : " " + f);139p = Runtime.getRuntime().exec(cmd);140BufferedReader in = new BufferedReader141(new InputStreamReader(p.getInputStream()));142String s;143int i = 0;144StringBuilder sb = new StringBuilder();145while ((s = in.readLine()) != null) {146// skip header147if (i++ == 0 && !name.startsWith("Windows")) continue;148sb.append(s).append("\n");149}150151Matcher m = dfPattern.matcher(sb);152int j = 0;153while (j < sb.length()) {154if (m.find(j)) {155if (!name.startsWith("Windows")) {156// swap can change while this test is running157if (!m.group(1).equals("swap")) {158String name = (f == null ? m.group(4): f);159al.add(new Space(m.group(2), m.group(3), name));;160}161} else {162String name = (f == null ? m.group(2) : f);163al.add(new Space(m.group(4), m.group(3), name ));;164}165j = m.end() + 1;166} else {167throw new RuntimeException("unrecognized df output format: "168+ "charAt(" + j + ") = '"169+ sb.charAt(j) + "'");170}171}172173if (al.size() == 0) {174// df did not produce output175String name = (f == null ? "" : f);176al.add(new Space("0", "0", name));177}178in.close();179return al;180}181182private static void tryCatch(Space s) {183out.format("%s:%n", s.name());184File f = new File(s.name());185SecurityManager sm = System.getSecurityManager();186if (sm instanceof Deny) {187String fmt = " %14s: \"%s\" thrown as expected%n";188try {189f.getTotalSpace();190fail(s.name(), SecurityException.class);191} catch (SecurityException x) {192out.format(fmt, "getTotalSpace", x);193pass();194}195try {196f.getFreeSpace();197fail(s.name(), SecurityException.class);198} catch (SecurityException x) {199out.format(fmt, "getFreeSpace", x);200pass();201}202try {203f.getUsableSpace();204fail(s.name(), SecurityException.class);205} catch (SecurityException x) {206out.format(fmt, "getUsableSpace", x);207pass();208}209}210}211212private static void compare(Space s) {213File f = new File(s.name());214long ts = f.getTotalSpace();215long fs = f.getFreeSpace();216long us = f.getUsableSpace();217218out.format("%s:%n", s.name());219String fmt = " %-4s total= %12d free = %12d usable = %12d%n";220out.format(fmt, "df", s.total(), 0, s.free());221out.format(fmt, "getX", ts, fs, us);222223// if the file system can dynamically change size, this check will fail224if (ts != s.total())225fail(s.name(), s.total(), "!=", ts);226else227pass();228229// unix df returns statvfs.f_bavail230long tsp = (!name.startsWith("Windows") ? us : fs);231if (!s.woomFree(tsp))232fail(s.name(), s.free(), "??", tsp);233else234pass();235236if (fs > s.total())237fail(s.name(), s.total(), ">", fs);238else239pass();240241if (us > s.total())242fail(s.name(), s.total(), ">", us);243else244pass();245}246247private static String FILE_PREFIX = "/getSpace.";248private static void compareZeroNonExist() {249File f;250while (true) {251f = new File(FILE_PREFIX + Math.random());252if (f.exists())253continue;254break;255}256257long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };258259for (int i = 0; i < s.length; i++) {260if (s[i] != 0L)261fail(f.getName(), s[i], "!=", 0L);262else263pass();264}265}266267private static void compareZeroExist() {268try {269File f = File.createTempFile("tmp", null, new File("."));270271long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };272273for (int i = 0; i < s.length; i++) {274if (s[i] == 0L)275fail(f.getName(), s[i], "==", 0L);276else277pass();278}279} catch (IOException x) {280fail("Couldn't create temp file for test");281}282}283284private static class Allow extends SecurityManager {285public void checkRead(String file) {}286public void checkPermission(Permission p) {}287public void checkPermission(Permission p, Object context) {}288}289290private static class Deny extends SecurityManager {291public void checkPermission(Permission p) {292if (p.implies(new RuntimePermission("setSecurityManager"))293|| p.implies(new RuntimePermission("getProtectionDomain")))294return;295super.checkPermission(p);296}297298public void checkPermission(Permission p, Object context) {299if (p.implies(new RuntimePermission("setSecurityManager"))300|| p.implies(new RuntimePermission("getProtectionDomain")))301return;302super.checkPermission(p, context);303}304}305306private static class DenyFSA extends Deny {307private String err = "sorry - getFileSystemAttributes";308309public void checkPermission(Permission p) {310if (p.implies(new RuntimePermission("getFileSystemAttributes")))311throw new SecurityException(err);312super.checkPermission(p);313}314315public void checkPermission(Permission p, Object context) {316if (p.implies(new RuntimePermission("getFileSystemAttributes")))317throw new SecurityException(err);318super.checkPermission(p, context);319}320}321322private static class DenyRead extends Deny {323private String err = "sorry - checkRead()";324325public void checkRead(String file) {326throw new SecurityException(err);327}328}329330private static void testFile(String dirName) {331out.format("--- Testing %s%n", dirName);332ArrayList l;333try {334l = space(dirName);335} catch (IOException x) {336throw new RuntimeException(dirName + " can't get file system information", x);337}338compare((GetXSpace.Space) l.get(0));339}340341private static void testDF() {342out.format("--- Testing df");343// Find all of the partitions on the machine and verify that the size344// returned by "df" is equivalent to File.getXSpace() values.345ArrayList l;346try {347l = space(null);348} catch (IOException x) {349throw new RuntimeException("can't get file system information", x);350}351if (l.size() == 0)352throw new RuntimeException("no partitions?");353354for (int i = 0; i < sma.length; i++) {355System.setSecurityManager(sma[i]);356SecurityManager sm = System.getSecurityManager();357if (sma[i] != null && sm == null)358throw new RuntimeException("Test configuration error "359+ " - can't set security manager");360361out.format("%nSecurityManager = %s%n" ,362(sm == null ? "null" : sm.getClass().getName()));363for (int j = 0; j < l.size(); j++) {364Space s = (GetXSpace.Space) l.get(j);365if (sm instanceof Deny) {366tryCatch(s);367} else {368compare(s);369compareZeroNonExist();370compareZeroExist();371}372}373}374}375376public static void main(String [] args) {377if (args.length > 0) {378testFile(args[0]);379} else {380testDF();381}382383if (fail != 0)384throw new RuntimeException((fail + pass) + " tests: "385+ fail + " failure(s), first", first);386else387out.format("all %d tests passed%n", fail + pass);388}389}390391392