29package com.jogamp.common.util;
31import java.io.BufferedInputStream;
32import java.io.BufferedOutputStream;
33import java.io.Closeable;
35import java.io.FileOutputStream;
36import java.io.FilePermission;
37import java.io.FileWriter;
38import java.io.IOException;
39import java.io.InputStream;
40import java.io.OutputStream;
41import java.io.PrintStream;
43import java.io.SyncFailedException;
44import java.lang.ref.WeakReference;
45import java.lang.reflect.Constructor;
46import java.lang.reflect.Method;
47import java.net.URISyntaxException;
49import java.net.URLConnection;
50import java.nio.ByteBuffer;
51import java.security.PrivilegedAction;
52import java.util.ArrayList;
54import java.util.Locale;
55import java.util.regex.Pattern;
57import jogamp.common.Debug;
58import jogamp.common.os.AndroidUtils;
59import jogamp.common.os.PlatformPropsImpl;
61import com.jogamp.common.ExceptionUtils;
62import com.jogamp.common.JogampRuntimeException;
63import com.jogamp.common.net.AssetURLContext;
64import com.jogamp.common.net.Uri;
65import com.jogamp.common.nio.Buffers;
66import com.jogamp.common.os.MachineDataInfo;
67import com.jogamp.common.os.Platform;
70 public static final boolean DEBUG;
71 private static final boolean DEBUG_EXE;
72 private static final boolean DEBUG_EXE_NOSTREAM;
73 private static final boolean DEBUG_EXE_EXISTING_FILE;
74 private static final boolean testTempDirExec;
75 private static final Method fileToPathGetter;
76 private static final Method isExecutableQuery;
77 private static final boolean useNativeExeFile;
80 final boolean _props[] = {
false,
false,
false,
false,
false,
false };
83 public Method[] run() {
84 final Method[] res =
new Method[] {
null,
null };
87 _props[i++] = Debug.debug(
"IOUtil");
97 res[i] = File.class.getDeclaredMethod(
"toPath");
98 res[i++].setAccessible(
true);
101 res[i] = nioFilesClz.getDeclaredMethod(
"isExecutable", nioPathClz);
102 res[i++].setAccessible(
true);
103 }
catch (
final Throwable t) {
114 DEBUG_EXE = _props[i++];
115 DEBUG_EXE_NOSTREAM = _props[i++];
116 DEBUG_EXE_EXISTING_FILE = _props[i++];
117 testTempDirExec = _props[i++];
118 useNativeExeFile = _props[i++];
121 fileToPathGetter = res[i++];
122 isExecutableQuery = res[i++];
127 private static final String java_io_tmpdir_propkey =
"java.io.tmpdir";
128 private static final String user_home_propkey =
"user.home";
129 private static final String XDG_CACHE_HOME_envkey =
"XDG_CACHE_HOME";
148 private static final Constructor<?> getFOSCtor() {
149 Constructor<?> _fosCtor;
152 _fosCtor =
ReflectionUtil.
getConstructor(
"java.io.FileOutputStream",
new Class<?>[] { File.class },
true, IOUtil.class.getClassLoader());
154 }
catch (
final Throwable t) {
159 System.err.println(
"IOUtil: java.io.FileOutputStream available: "+(
null != _fosCtor));
161 _t.printStackTrace();
182 public static int copyURLConn2File(
final URLConnection conn,
final File outFile)
throws IOException {
185 int totalNumBytes = 0;
186 final InputStream in =
new BufferedInputStream(conn.getInputStream());
192 return totalNumBytes;
204 public static int copyStream2File(
final InputStream in,
final File outFile)
throws IOException {
205 final OutputStream out =
new BufferedOutputStream(
new FileOutputStream(outFile));
222 public static int copyStream2Stream(
final InputStream in,
final OutputStream out)
throws IOException {
236 public static int copyStream2Stream(
final int bufferSize,
final InputStream in,
final OutputStream out)
throws IOException {
237 final byte[] buf =
new byte[bufferSize];
241 if ((count = in.read(buf)) == -1) {
244 out.write(buf, 0, count);
250 public static StringBuilder
appendCharStream(
final StringBuilder sb,
final Reader r)
throws IOException {
251 final char[] cbuf =
new char[1024];
253 while( 0 < ( count = r.read(cbuf) ) ) {
254 sb.append(cbuf, 0, count);
263 if( !(stream instanceof BufferedInputStream) ) {
264 stream =
new BufferedInputStream(stream);
267 int avail = stream.available();
268 byte[] data =
new byte[avail];
271 if (totalRead + avail > data.length) {
272 final byte[] newData =
new byte[totalRead + avail];
273 System.arraycopy(data, 0, newData, 0, totalRead);
276 numRead = stream.read(data, totalRead, avail);
278 totalRead += numRead;
280 avail = stream.available();
281 }
while (avail > 0 && numRead >= 0);
284 if (totalRead != data.length) {
285 final byte[] newData =
new byte[totalRead];
286 System.arraycopy(data, 0, newData, 0, totalRead);
308 if( !(stream instanceof BufferedInputStream) ) {
309 stream =
new BufferedInputStream(stream);
311 int avail = stream.available();
312 if( initialCapacity < avail ) {
313 initialCapacity = avail;
317 final byte[] chunk =
new byte[machine.pageSizeInBytes()];
318 int chunk2Read = Math.min(machine.pageSizeInBytes(), avail);
321 if (avail > data.remaining()) {
328 numRead = stream.read(chunk, 0, chunk2Read);
330 data.put(chunk, 0, numRead);
332 avail = stream.available();
333 chunk2Read = Math.min(machine.pageSizeInBytes(), avail);
334 }
while ( numRead > 0 );
348 if( !(stream instanceof BufferedInputStream) ) {
349 stream =
new BufferedInputStream(stream);
353 final byte[] chunk =
new byte[machine.pageSizeInBytes()];
355 while ( numRead > 0 && skipBytes > 0 ) {
356 final int chunk2Read = Math.min(machine.pageSizeInBytes(), skipBytes);
357 numRead = stream.read(chunk, 0, chunk2Read);
358 skipBytes -= numRead;
360 while ( numRead > 0 && byteCount > 0 ) {
361 final int chunk2Read = Math.min(machine.pageSizeInBytes(), byteCount);
362 numRead = stream.read(chunk, 0, chunk2Read);
364 data.put(chunk, 0, numRead);
366 byteCount -= numRead;
379 private static final Pattern patternSingleBS = Pattern.compile(
"\\\\{1}");
389 public static String
slashify(
final String path,
final boolean startWithSlash,
final boolean endWithSlash)
throws URISyntaxException {
390 String p = patternSingleBS.matcher(path).replaceAll(
"/");
391 if (startWithSlash && !p.startsWith(
"/")) {
394 if (endWithSlash && !p.endsWith(
"/")) {
426 final int lastDot = filename.lastIndexOf(
'.');
430 return toLowerCase(filename.substring(lastDot + 1));
432 private static String toLowerCase(
final String arg) {
437 return arg.toLowerCase();
448 public static FileOutputStream
getFileOutputStream(
final File file,
final boolean allowOverwrite)
throws IOException {
449 final Constructor<?> fosCtor = getFOSCtor();
450 if(
null == fosCtor) {
451 throw new IOException(
"Cannot open file (" + file +
") for writing, FileOutputStream feature not available.");
453 if (file.exists() && !allowOverwrite) {
454 throw new IOException(
"File already exists (" + file +
") and overwrite=false");
457 return (FileOutputStream) fosCtor.newInstance(
new Object[] { file });
458 }
catch (
final Exception e) {
459 throw new IOException(
"error opening " + file +
" for write. ", e);
465 return clazzBinName.replace(
'.',
'/') +
".class";
474 public static URL
getClassURL(
final String clazzBinName,
final ClassLoader cl)
throws IOException {
477 throw new IOException(
"Cannot not find: "+clazzBinName);
486 public static String
getBasename(String fname)
throws URISyntaxException {
487 fname =
slashify(fname,
false ,
false );
488 final int lios = fname.lastIndexOf(
'/');
490 fname = fname.substring(lios+1);
499 public static String
getDirname(String fname)
throws URISyntaxException {
500 fname =
slashify(fname,
false ,
false );
501 final int lios = fname.lastIndexOf(
'/');
503 fname = fname.substring(0, lios+1);
539 throw new IllegalArgumentException(
"resourcePath["+i+
"] is null");
543 this.contextCL = relContext;
552 public URLConnection
resolve(
final int uriIndex)
throws ArrayIndexOutOfBoundsException {
578 public static URLConnection
getResource(
final String resourcePath,
final ClassLoader classLoader,
final Class<?> relContext) {
579 if(
null == resourcePath) {
582 URLConnection conn =
null;
583 if(
null != relContext) {
585 final String className = relContext.getName().replace(
'.',
'/');
586 final int lastSlash = className.lastIndexOf(
'/');
587 if (lastSlash >= 0) {
588 final String pkgName = className.substring(0, lastSlash + 1);
589 conn =
getResource(pkgName + resourcePath, classLoader);
591 System.err.println(
"IOUtil: found <"+resourcePath+
"> within class package <"+pkgName+
"> of given class <"+relContext.getName()+
">: "+(
null!=conn));
595 System.err.println(
"IOUtil: null context, skip rel. lookup");
600 System.err.println(
"IOUtil: found <"+resourcePath+
"> by classloader: "+(
null!=conn));
617 public static URLConnection
getResource(
final String resourcePath,
final ClassLoader cl) {
618 if(
null == resourcePath) {
622 System.err.println(
"IOUtil: locating <"+resourcePath+
">, has cl: "+(
null!=cl));
627 }
catch (
final IOException ioe) {
636 }
catch (
final IOException ioe) {
652 public static String
getRelativeOf(
final File baseLocation,
final String relativeFile)
throws URISyntaxException {
653 if(
null == relativeFile) {
657 if (baseLocation !=
null) {
658 final File file =
new File(baseLocation, relativeFile);
660 return slashify(file.getPath(),
false ,
false );
670 public static String
getParentOf(
final String path)
throws URISyntaxException {
671 final int pl =
null!=path ? path.length() : 0;
673 throw new IllegalArgumentException(
"path is empty <"+path+
">");
676 final int e = path.lastIndexOf(
"/");
678 throw new URISyntaxException(path,
"path contains no '/': <"+path+
">");
682 throw new URISyntaxException(path,
"path has no parents: <"+path+
">");
686 return path.substring(0, e+1);
688 final int j = path.lastIndexOf(
"!") + 1;
690 final int p = path.lastIndexOf(
"/", e-1);
693 return path.substring(0, p+1);
696 final String parent = path.substring(j, e);
697 if( parent.equals(
"..") ) {
698 throw new URISyntaxException(path,
"parent is unresolved: <"+path+
">");
701 return path.substring(0, j);
714 int idx = path.length() - 1;
715 while ( idx >= 1 && ( idx = path.lastIndexOf(
"./", idx) ) >= 0 ) {
716 if( 0 < idx && path.charAt(idx-1) ==
'.' ) {
719 path = path.substring(0, idx) + path.substring(idx+2);
724 while ( ( idx = path.indexOf(
"../", idx) ) >= 0 ) {
728 path =
getParentOf(path.substring(0, idx)) + path.substring(idx+3);
746 return uri.
toFile().getPath();
755 public static URLConnection
openURL(
final URL url) {
762 public static URLConnection
openURL(
final URL url,
final String dbgmsg) {
765 final URLConnection c = url.openConnection();
768 System.err.println(
"IOUtil: urlExists("+url+
") ["+dbgmsg+
"] - true");
771 }
catch (
final IOException ioe) {
777 System.err.println(
"IOUtil: no url - urlExists(null) ["+dbgmsg+
"]");
783 private static String getExeTestFileSuffix() {
784 switch(PlatformPropsImpl.OS_TYPE) {
795 private static String getExeTestShellCode() {
796 switch(PlatformPropsImpl.OS_TYPE) {
798 return "echo off"+PlatformPropsImpl.NEWLINE;
800 return "#!/bin/true"+PlatformPropsImpl.NEWLINE;
803 private static String getExeNativePath(
final String canonicalPath) {
804 switch(PlatformPropsImpl.OS_TYPE) {
806 return "\""+canonicalPath+
"\"";
808 return canonicalPath;
811 private static String[] getExeTestCommandArgs(
final String scriptFile) {
812 switch(PlatformPropsImpl.OS_TYPE) {
816 return new String[] { scriptFile };
820 private static final byte[] readCode(
final String fname)
throws IOException {
821 final URLConnection con = IOUtil.getResource(fname, IOUtil.class.getClassLoader(), IOUtil.class);
822 final InputStream in = con.getInputStream();
823 byte[] output =
null;
825 output = CustomCompress.inflateFromStream(in);
831 private static final Object exeTestLock =
new Object();
832 private static WeakReference<byte[]> exeTestCodeRef =
null;
834 private static void fillExeTestFile(
final File exefile)
throws IOException {
835 if( useNativeExeFile &&
836 Platform.OSType.WINDOWS == PlatformPropsImpl.OS_TYPE &&
837 Platform.CPUFamily.X86 == PlatformPropsImpl.CPU_ARCH.family
839 final byte[] exeTestCode;
840 synchronized ( exeTestLock ) {
841 byte[] _exeTestCode =
null;
842 if(
null == exeTestCodeRef ||
null == ( _exeTestCode = exeTestCodeRef.get() ) ) {
844 if( Platform.CPUType.X86_64 == PlatformPropsImpl.CPU_ARCH ) {
845 fname =
"bin/exe-windows-x86_64.defl";
847 fname =
"bin/exe-windows-i386.defl";
849 exeTestCode = readCode(fname);
850 exeTestCodeRef =
new WeakReference<byte[]>(exeTestCode);
852 exeTestCode = _exeTestCode;
855 final FileOutputStream out =
new FileOutputStream(exefile);
857 out.write(exeTestCode, 0, exeTestCode.length);
860 }
catch (
final SyncFailedException sfe) {
861 ExceptionUtils.dumpThrowable(
"", sfe);
867 final String shellCode = getExeTestShellCode();
868 if( isStringSet(shellCode) ) {
869 final FileWriter fout =
new FileWriter(exefile);
871 fout.write(shellCode);
874 }
catch (
final IOException sfe) {
875 ExceptionUtils.dumpThrowable(
"", sfe);
883 private static boolean getOSHasNoexecFS() {
884 switch(PlatformPropsImpl.OS_TYPE) {
896 private static boolean getOSHasFreeDesktopXDG() {
897 switch(PlatformPropsImpl.OS_TYPE) {
918 public static boolean testFile(
final File file,
final boolean shallBeDir,
final boolean shallBeWritable) {
919 if (!file.exists()) {
921 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: does not exist");
925 if (shallBeDir && !file.isDirectory()) {
927 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: is not a directory");
931 if (shallBeWritable && !file.canWrite()) {
933 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: is not writable");
941 private final InputStream[] istreams;
942 private final boolean[] eos;
943 private final PrintStream ostream;
944 private final String prefix;
945 public StreamMonitor(
final InputStream[] streams,
final PrintStream ostream,
final String prefix) {
946 this.istreams = streams;
947 this.eos =
new boolean[streams.length];
948 this.ostream = ostream;
949 this.prefix = prefix;
950 final InterruptSource.Thread t =
new InterruptSource.
Thread(
null,
this,
"StreamMonitor-"+Thread.currentThread().getName());
958 final byte[] buffer =
new byte[4096];
960 final int streamCount = istreams.length;
963 for(
int i=0; i<istreams.length; i++) {
965 final int numReadI = istreams[i].read(buffer);
967 if(
null != ostream ) {
968 if(
null != prefix ) {
969 ostream.write(prefix.getBytes());
971 ostream.write(buffer, 0, numReadI);
980 if(
null != ostream ) {
983 }
while ( eosCount < streamCount );
984 }
catch (
final IOException e) {
986 if(
null != ostream ) {
994 private static final Boolean isNioExecutableFile(
final File file) {
995 if(
null != fileToPathGetter &&
null != isExecutableQuery ) {
997 return (Boolean) isExecutableQuery.invoke(
null, fileToPathGetter.invoke(file));
998 }
catch (
final Throwable t) {
1019 throws SecurityException
1021 final boolean debug = DEBUG_EXE ||
DEBUG;
1023 if( !testTempDirExec ) {
1025 System.err.println(
"IOUtil.testDirExec: <"+dir.getAbsolutePath()+
">: Disabled TestTempDirExec");
1031 System.err.println(
"IOUtil.testDirExec: <"+dir.getAbsolutePath()+
">: Not writeable dir");
1035 if(!getOSHasNoexecFS()) {
1037 System.err.println(
"IOUtil.testDirExec: <"+dir.getAbsolutePath()+
">: Always executable");
1042 final long t0 = debug ? System.currentTimeMillis() : 0;
1043 final File exeTestFile;
1044 String exeNativePath;
1045 final boolean existingExe;
1047 final File permExeTestFile = DEBUG_EXE_EXISTING_FILE ?
new File(dir,
"jogamp_exe_tst"+getExeTestFileSuffix()) :
null;
1048 if(
null != permExeTestFile && permExeTestFile.exists() ) {
1049 exeTestFile = permExeTestFile;
1052 exeTestFile = File.createTempFile(
"jogamp_exe_tst", getExeTestFileSuffix(), dir);
1053 existingExe =
false;
1054 fillExeTestFile(exeTestFile);
1056 exeNativePath = getExeNativePath( exeTestFile.getCanonicalPath() );
1057 }
catch (
final SecurityException se) {
1059 }
catch (
final IOException e) {
1061 e.printStackTrace();
1065 final long t1 = debug ? System.currentTimeMillis() : 0;
1069 Boolean isNioExec =
null;
1070 if( existingExe || exeTestFile.setExecutable(
true ,
true ) ) {
1071 t2 = debug ? System.currentTimeMillis() : 0;
1073 isNioExec = isNioExecutableFile(exeTestFile);
1074 if(
null != isNioExec ) {
1075 res = isNioExec.booleanValue() ? 0 : -1;
1077 if(
null == isNioExec || 0 <= res ) {
1085 pr = Runtime.getRuntime().exec( getExeTestCommandArgs( exeNativePath ),
null,
null );
1086 if( DEBUG_EXE && !DEBUG_EXE_NOSTREAM ) {
1087 new StreamMonitor(
new InputStream[] { pr.getInputStream(), pr.getErrorStream() }, System.err,
"Exe-Tst: ");
1090 exitValue = pr.exitValue();
1091 if( 0 == exitValue ) {
1096 }
catch (
final SecurityException se) {
1098 }
catch (
final Throwable t) {
1099 t2 = debug ? System.currentTimeMillis() : 0;
1102 System.err.println(
"IOUtil.testDirExec: <"+exeNativePath+
">: Caught "+t.getClass().getSimpleName()+
": "+t.getMessage());
1103 t.printStackTrace();
1112 }
catch (
final Throwable t) {
1119 t2 = debug ? System.currentTimeMillis() : 0;
1122 final boolean ok = 0 <= res;
1123 if( !DEBUG_EXE && !existingExe ) {
1124 exeTestFile.delete();
1127 final long t3 = System.currentTimeMillis();
1128 System.err.println(
"IOUtil.testDirExec(): test-exe <"+exeNativePath+
">, existingFile "+existingExe+
", isNioExec "+isNioExec+
", returned "+exitValue);
1129 System.err.println(
"IOUtil.testDirExec(): abs-path <"+dir.getAbsolutePath()+
">: res "+res+
" -> "+ok);
1130 System.err.println(
"IOUtil.testDirExec(): total "+(t3-t0)+
"ms, create "+(t1-t0)+
"ms, fill "+(t2-t1)+
"ms, execute "+(t3-t2)+
"ms");
1135 private static File testDirImpl(
final File dir,
final boolean create,
final boolean executable,
final String dbgMsg)
1136 throws SecurityException
1139 if (create && !dir.exists()) {
1145 res =
testFile(dir,
true,
true) ? dir :
null;
1148 System.err.println(
"IOUtil.testDirImpl("+dbgMsg+
"): <"+dir.getAbsolutePath()+
">, create "+create+
", exec "+executable+
": "+(
null != res));
1167 public static File
testDir(
final File dir,
final boolean create,
final boolean executable)
1168 throws SecurityException
1170 return testDirImpl(dir, create, executable,
"testDir");
1173 private static boolean isStringSet(
final String s) {
return null != s && 0 < s.length(); }
1199 private static File getSubTempDir(
final File tmpRoot,
final String tmpSubDirPrefix,
final boolean executable,
final String dbgMsg)
1200 throws SecurityException
1202 File tmpBaseDir =
null;
1203 if(
null != testDirImpl(tmpRoot,
true , executable, dbgMsg)) {
1204 for(
int i = 0;
null == tmpBaseDir && i<=9999; i++) {
1205 final String tmpDirSuffix = String.format((Locale)
null,
"_%04d", i);
1206 tmpBaseDir = testDirImpl(
new File(tmpRoot, tmpSubDirPrefix+tmpDirSuffix),
true , executable, dbgMsg);
1212 private static File getFile(
final String fname) {
1213 if( isStringSet(fname) ) {
1214 return new File(fname);
1247 throws SecurityException, IOException
1250 synchronized(
IOUtil.class) {
1254 final File ctxTempDir = AndroidUtils.getTempRoot();
1255 if(
null != ctxTempDir) {
1256 tempRootNoexec = getSubTempDir(ctxTempDir,
tmpSubDir,
false ,
"Android.ctxTemp");
1257 tempRootExec = tempRootNoexec;
1258 return tempRootExec;
1264 System.err.println(
"IOUtil.getTempRoot(): tempX1 <"+java_io_tmpdir+
">, used "+(
null!=java_io_tmpdir));
1267 final File user_tmpdir;
1269 String __user_tmpdir = System.getenv(
"TMPDIR");
1270 if( !isStringSet(__user_tmpdir) ) {
1271 __user_tmpdir = System.getenv(
"TEMP");
1273 final File _user_tmpdir = getFile(__user_tmpdir);
1274 if(
null != _user_tmpdir && !_user_tmpdir.equals(java_io_tmpdir) ) {
1275 user_tmpdir = _user_tmpdir;
1280 System.err.println(
"IOUtil.getTempRoot(): tempX3 <"+_user_tmpdir+
">, used "+(
null!=user_tmpdir));
1286 System.err.println(
"IOUtil.getTempRoot(): tempX4 <"+user_home+
">, used "+(
null!=user_home));
1289 final File xdg_cache_home;
1291 String __xdg_cache_home;
1292 if( getOSHasFreeDesktopXDG() ) {
1293 __xdg_cache_home = System.getenv(XDG_CACHE_HOME_envkey);
1294 if( !isStringSet(__xdg_cache_home) &&
null != user_home ) {
1295 __xdg_cache_home = user_home.getAbsolutePath() + File.separator +
".cache" ;
1298 __xdg_cache_home =
null;
1300 final File _xdg_cache_home = getFile(__xdg_cache_home);
1301 if(
null != _xdg_cache_home && !_xdg_cache_home.equals(java_io_tmpdir) ) {
1302 xdg_cache_home = _xdg_cache_home;
1304 xdg_cache_home =
null;
1307 System.err.println(
"IOUtil.getTempRoot(): tempX2 <"+_xdg_cache_home+
">, used "+(
null!=xdg_cache_home));
1312 if(
null == tempRootExec &&
null != java_io_tmpdir ) {
1316 tempRootExec = getSubTempDir(java_io_tmpdir,
tmpSubDir,
false ,
"tempX1");
1318 tempRootExec = getSubTempDir(java_io_tmpdir,
tmpSubDir,
true ,
"tempX1");
1323 if(
null == tempRootExec &&
null != xdg_cache_home ) {
1324 tempRootExec = getSubTempDir(xdg_cache_home,
tmpSubDir,
true ,
"tempX2");
1328 if(
null == tempRootExec &&
null != user_tmpdir ) {
1329 tempRootExec = getSubTempDir(user_tmpdir,
tmpSubDir,
true ,
"tempX3");
1333 if(
null == tempRootExec &&
null != user_home ) {
1334 tempRootExec = getSubTempDir(user_home,
"." +
tmpSubDir,
true ,
"tempX4");
1337 if(
null != tempRootExec ) {
1338 tempRootNoexec = tempRootExec;
1341 if(
null == tempRootNoexec &&
null != java_io_tmpdir ) {
1342 tempRootNoexec = getSubTempDir(java_io_tmpdir,
tmpSubDir,
false ,
"temp01");
1346 if(
null == tempRootNoexec &&
null != xdg_cache_home ) {
1347 tempRootNoexec = getSubTempDir(xdg_cache_home,
tmpSubDir,
false ,
"temp02");
1351 if(
null == tempRootNoexec &&
null != user_tmpdir ) {
1352 tempRootNoexec = getSubTempDir(user_tmpdir,
tmpSubDir,
false ,
"temp03");
1356 if(
null == tempRootNoexec &&
null != user_home ) {
1357 tempRootNoexec = getSubTempDir(user_home,
"." +
tmpSubDir,
false ,
"temp04");
1362 final String tempRootExecAbsPath =
null != tempRootExec ? tempRootExec.getAbsolutePath() :
null;
1363 final String tempRootNoexecAbsPath =
null != tempRootNoexec ? tempRootNoexec.getAbsolutePath() :
null;
1364 System.err.println(
"IOUtil.getTempRoot(): temp dirs: exec: "+tempRootExecAbsPath+
", noexec: "+tempRootNoexecAbsPath);
1369 final File r = executable ? tempRootExec : tempRootNoexec ;
1371 final String exe_s = executable ?
"executable " :
"";
1372 throw new IOException(
"Could not determine a temporary "+exe_s+
"directory");
1374 final FilePermission fp =
new FilePermission(r.getAbsolutePath(),
"read,write,delete");
1378 private static File tempRootExec =
null;
1379 private static File tempRootNoexec =
null;
1380 private static volatile boolean tempRootSet =
false;
1399 public static File
createTempFile(
final String prefix,
final String suffix,
final boolean executable)
1400 throws IllegalArgumentException, IOException, SecurityException
1402 return File.createTempFile( prefix, suffix,
getTempDir(executable) );
1405 public static void close(
final Closeable stream,
final boolean throwRuntimeException)
throws RuntimeException {
1406 if(
null != stream) {
1409 }
catch (
final IOException e) {
1410 if(throwRuntimeException) {
1411 throw new RuntimeException(e);
1413 System.err.println(
"Caught Exception: ");
1414 e.printStackTrace();
1428 public static IOException
close(
final Closeable stream,
final IOException[] saveOneIfFree,
final PrintStream dumpExcess) {
1431 }
catch(
final IOException e) {
1432 if(
null == saveOneIfFree[0] ) {
1433 saveOneIfFree[0] = e;
1435 if(
null != dumpExcess ) {
1436 dumpExcess.println(
"Caught "+e.getClass().getSimpleName()+
": "+e.getMessage());
1437 e.printStackTrace(dumpExcess);
1452 public static ArrayList<String>
filesOf(
final List<String> paths,
final List<Pattern> excludes,
final List<Pattern> includes) {
1453 final ArrayList<String> files =
new ArrayList<String>(paths.size()*32);
1454 final ArrayList<String> todo =
new ArrayList<String>(paths);
1455 while(todo.size() > 0) {
1456 final String p = todo.remove(0);
1457 if(
null != excludes && excludes.size() > 0) {
1458 boolean exclude =
false;
1459 for(
int i=0; !exclude && i<excludes.size(); i++) {
1460 exclude = excludes.get(i).matcher(p).matches();
1463 System.err.println(
"IOUtil.filesOf(): excluding <"+p+
"> (exclude["+i+
"]: "+excludes.get(i)+
")");
1471 final File f =
new File(p);
1474 System.err.println(
"IOUtil.filesOf(): not existing: "+f);
1477 }
else if( f.isDirectory() ) {
1478 final String[] subs = f.list();
1479 if(
null == subs ) {
1481 System.err.println(
"IOUtil.filesOf(): null list of directory: "+f);
1483 }
else if( 0 == subs.length ) {
1485 System.err.println(
"IOUtil.filesOf(): empty list of directory: "+f);
1489 final String pp = p.endsWith(
"/") ? p : p+
"/";
1490 for(
int i=0; i<subs.length; i++) {
1491 todo.add(j++, pp+subs[i]);
1495 if(
null != includes && includes.size() > 0) {
1496 boolean include =
false;
1497 for(
int i=0; !include && i<includes.size(); i++) {
1498 include = includes.get(i).matcher(p).matches();
1501 System.err.println(
"IOUtil.filesOf(): including <"+p+
"> (including["+i+
"]: "+includes.get(i)+
")");
static void dumpThrowable(final String additionalDescr, final Throwable t)
Dumps a Throwable to System.err in a decorating message including the current thread name,...
A generic unchecked exception for Jogamp errors used throughout the binding as a substitute for Runti...
See PiggybackURLConnection for description and examples.
static final String asset_protocol_prefix
The asset URL protocol prefix asset:
static URL createURL(final String path, final ClassLoader cl)
Create an asset URL, suitable even w/o the registered asset URLStreamHandler.
URLConnection resolve(final String path)
Resolving path to a URL sub protocol and return it's open URLConnection.
final String get()
Returns the encoded String.
This class implements an immutable Uri as defined by RFC 2396.
ASCIIEncoded toASCIIString()
Returns the encoded input encoded in US-ASCII.
final boolean isFileScheme()
Returns true, if this instance is a file scheme, otherwise false.
final File toFile()
If this instance is a file scheme, implementation decodes [ "//"+authority ] + path,...
Utility methods allowing easy java.nio.Buffer manipulations.
static ByteBuffer newDirectByteBuffer(final int numElements)
Allocates a new direct ByteBuffer with the specified number of elements.
Machine data description for alignment and size onle, see com.jogamp.gluegen.
int pageAlignedSize(final int size)
Helper compound associating a class instance and resource paths to be resolved at a later time.
final int resourceCount()
Returns the number of resources, i.e.
final String[] resourcePaths
Resource paths, see resolve(int).
URLConnection resolve(final int uriIndex)
Resolving one of the resourcePaths indexed by uriIndex using classLoader, contextCL through IOUtil#ge...
final ClassLoader classLoader
Optional ClassLoader used to resolve(int) resourcePaths.
ClassResources(final String[] resourcePaths, final ClassLoader classLoader, final Class<?> relContext)
final Class<?> contextCL
Optional class instance used to resolve(int) relative resourcePaths.
StreamMonitor(final InputStream[] streams, final PrintStream ostream, final String prefix)
static FileOutputStream getFileOutputStream(final File file, final boolean allowOverwrite)
static String cleanPathString(String path)
static int copyStream2Stream(final int bufferSize, final InputStream in, final OutputStream out)
Copy the complete specified input stream to the specified output stream.
static ByteBuffer copyStream2ByteBuffer(InputStream stream, int initialCapacity)
Copy the complete specified input stream to a NIO ByteBuffer w/ native byte order,...
static File createTempFile(final String prefix, final String suffix, final boolean executable)
Utilizing File#createTempFile(String, String, File) using getTempDir(boolean) as the directory parame...
static String getBasename(String fname)
Returns the basename of the given fname w/o directory part.
static final String tmpSubDir
Subdirectory within platform's temporary root directory where all JogAmp related temp files are being...
static URL getClassURL(final String clazzBinName, final ClassLoader cl)
static URLConnection openURL(final URL url, final String dbgmsg)
Returns the connected URLConnection, or null if not url is not available.
static URLConnection getResource(final String resourcePath, final ClassLoader cl)
Locating a resource using the ClassLoader's facilities.
static final boolean DEBUG
static boolean testFile(final File file, final boolean shallBeDir, final boolean shallBeWritable)
Test whether file exists and matches the given requirements.
static URLConnection getResource(final String resourcePath, final ClassLoader classLoader, final Class<?> relContext)
Locating a resource using getResource(String, ClassLoader):
static String getRelativeOf(final File baseLocation, final String relativeFile)
Generates a path for the 'relativeFile' relative to the 'baseLocation'.
static File getTempDir(final boolean executable)
Returns a platform independent writable directory for temporary files consisting of the platform's te...
static String getParentOf(final String path)
static int copyStream2Stream(final InputStream in, final OutputStream out)
Copy the complete specified input stream to the specified output stream.
static String getFileSuffix(final File file)
Returns the lowercase suffix of the given file name (the text after the last '.
static String slashify(final String path, final boolean startWithSlash, final boolean endWithSlash)
static URLConnection openURL(final URL url)
Returns the connected URLConnection, or null if not url is not available.
static ByteBuffer copyStream2ByteBuffer(final InputStream stream)
Copy the complete specified input stream to a NIO ByteBuffer w/ native byte order,...
static void close(final Closeable stream, final boolean throwRuntimeException)
static String getClassFileName(final String clazzBinName)
static String getDirname(String fname)
Returns unified '/' dirname including the last '/'.
static ByteBuffer copyStreamChunk2ByteBuffer(InputStream stream, int skipBytes, int byteCount)
Copy the specified input stream chunk to a NIO ByteBuffer w/ native byte order, which is being return...
static String getFileSuffix(final String filename)
Returns the lowercase suffix of the given file name (the text after the last '.
static boolean testDirExec(final File dir)
Returns true if the given dir @endiliteral.
static final Pattern patternSpaceEnc
static File testDir(final File dir, final boolean create, final boolean executable)
Returns the directory dir, which is processed and tested as described below.
static ArrayList< String > filesOf(final List< String > paths, final List< Pattern > excludes, final List< Pattern > includes)
Retrieve the list of all filenames traversing through given paths.
static String getUriFilePathOrASCII(final Uri uri)
If uri is a file scheme implementation returns Uri#toFile().
static int copyURLConn2File(final URLConnection conn, final File outFile)
Copy the complete specified URL resource to the specified output file.
static byte[] copyStream2ByteArray(InputStream stream)
Copy the complete specified input stream to a byte array, which is being returned.
static StringBuilder appendCharStream(final StringBuilder sb, final Reader r)
static int copyStream2File(final InputStream in, final File outFile)
Copy the complete specified input stream to the specified output file.
static IOException close(final Closeable stream, final IOException[] saveOneIfFree, final PrintStream dumpExcess)
Helper to simplify closing Closeables.
java.lang.Thread specialization implementing InterruptSource to track java.lang.Thread#interrupt() ca...
Helper routines for accessing properties.
static final boolean getBooleanProperty(final String property, final boolean jnlpAlias)
static final boolean isPropertyDefined(final String property, final boolean jnlpAlias)
static final String getProperty(final String propertyKey, final boolean jnlpAlias)
Query the property with the name propertyKey.
static final Constructor<?> getConstructor(final String clazzName, final Class<?>[] cstrArgTypes, final boolean initializeClazz, final ClassLoader cl)
static final Class<?> getClass(final String clazzName, final boolean initializeClazz, final ClassLoader cl)
Loads and returns the class or null.
static< T > T doPrivileged(final PrivilegedAction< T > o)
Call wrapper for java.security.AccessController#doPrivileged(PrivilegedAction).
static final void checkPermission(final Permission perm)
Throws an SecurityException if an installed SecurityManager does not permit the requested Permission.
Interface exposing java.lang.Thread#interrupt() source, intended for java.lang.Thread specializations...