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 getExeTestShellCodeUnix(
final String test) {
797 return "#!"+test+PlatformPropsImpl.NEWLINE;
801 private static String getExeTestShellCode() {
802 if( PlatformPropsImpl.OS_TYPE == Platform.OSType.WINDOWS ) {
803 return "echo off"+PlatformPropsImpl.NEWLINE;
805 final String res = getExeTestShellCodeUnix(
"/usr/bin/true");
809 return getExeTestShellCodeUnix(
"/bin/true");
811 private static String getExeNativePath(
final String canonicalPath) {
812 switch(PlatformPropsImpl.OS_TYPE) {
814 return "\""+canonicalPath+
"\"";
816 return canonicalPath;
819 private static String[] getExeTestCommandArgs(
final String scriptFile) {
820 switch(PlatformPropsImpl.OS_TYPE) {
824 return new String[] { scriptFile };
828 private static final byte[] readCode(
final String fname)
throws IOException {
829 final URLConnection con = IOUtil.getResource(fname, IOUtil.class.getClassLoader(), IOUtil.class);
830 final InputStream in = con.getInputStream();
831 byte[] output =
null;
833 output = CustomCompress.inflateFromStream(in);
839 private static final Object exeTestLock =
new Object();
840 private static WeakReference<byte[]> exeTestCodeRef =
null;
842 private static void fillExeTestFile(
final File exefile)
throws IOException {
843 if( useNativeExeFile &&
844 Platform.OSType.WINDOWS == PlatformPropsImpl.OS_TYPE &&
845 Platform.CPUFamily.X86 == PlatformPropsImpl.CPU_ARCH.family
847 final byte[] exeTestCode;
848 synchronized ( exeTestLock ) {
849 byte[] _exeTestCode =
null;
850 if(
null == exeTestCodeRef ||
null == ( _exeTestCode = exeTestCodeRef.get() ) ) {
852 if( Platform.CPUType.X86_64 == PlatformPropsImpl.CPU_ARCH ) {
853 fname =
"bin/exe-windows-x86_64.defl";
855 fname =
"bin/exe-windows-i386.defl";
857 exeTestCode = readCode(fname);
858 exeTestCodeRef =
new WeakReference<byte[]>(exeTestCode);
860 exeTestCode = _exeTestCode;
863 final FileOutputStream out =
new FileOutputStream(exefile);
865 out.write(exeTestCode, 0, exeTestCode.length);
868 }
catch (
final SyncFailedException sfe) {
869 ExceptionUtils.dumpThrowable(
"", sfe);
875 final String shellCode = getExeTestShellCode();
876 if( isStringSet(shellCode) ) {
877 final FileWriter fout =
new FileWriter(exefile);
879 fout.write(shellCode);
882 }
catch (
final IOException sfe) {
883 ExceptionUtils.dumpThrowable(
"", sfe);
891 private static boolean getOSHasNoexecFS() {
892 switch(PlatformPropsImpl.OS_TYPE) {
904 private static boolean getOSHasFreeDesktopXDG() {
905 switch(PlatformPropsImpl.OS_TYPE) {
926 public static boolean testFile(
final File file,
final boolean shallBeDir,
final boolean shallBeWritable) {
927 if (!file.exists()) {
929 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: does not exist");
933 if (shallBeDir && !file.isDirectory()) {
935 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: is not a directory");
939 if (shallBeWritable && !file.canWrite()) {
941 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: is not writable");
954 if (!file.exists()) {
956 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: does not exist");
960 if (!file.canExecute()) {
962 System.err.println(
"IOUtil.testFile: <"+file.getAbsolutePath()+
">: can't be executed");
970 private final InputStream[] istreams;
971 private final boolean[] eos;
972 private final PrintStream ostream;
973 private final String prefix;
974 public StreamMonitor(
final InputStream[] streams,
final PrintStream ostream,
final String prefix) {
975 this.istreams = streams;
976 this.eos =
new boolean[streams.length];
977 this.ostream = ostream;
978 this.prefix = prefix;
979 final InterruptSource.Thread t =
new InterruptSource.
Thread(
null,
this,
"StreamMonitor-"+Thread.currentThread().getName());
987 final byte[] buffer =
new byte[4096];
989 final int streamCount = istreams.length;
992 for(
int i=0; i<istreams.length; i++) {
994 final int numReadI = istreams[i].read(buffer);
996 if(
null != ostream ) {
997 if(
null != prefix ) {
998 ostream.write(prefix.getBytes());
1000 ostream.write(buffer, 0, numReadI);
1009 if(
null != ostream ) {
1012 }
while ( eosCount < streamCount );
1013 }
catch (
final IOException e) {
1015 if(
null != ostream ) {
1023 private static final Boolean isNioExecutableFile(
final File file) {
1024 if(
null != fileToPathGetter &&
null != isExecutableQuery ) {
1026 return (Boolean) isExecutableQuery.invoke(
null, fileToPathGetter.invoke(file));
1027 }
catch (
final Throwable t) {
1048 throws SecurityException
1050 final boolean debug = DEBUG_EXE ||
DEBUG;
1052 if( !testTempDirExec ) {
1054 System.err.println(
"IOUtil.testDirExec: <"+dir.getAbsolutePath()+
">: Disabled TestTempDirExec");
1060 System.err.println(
"IOUtil.testDirExec: <"+dir.getAbsolutePath()+
">: Not writeable dir");
1064 if(!getOSHasNoexecFS()) {
1066 System.err.println(
"IOUtil.testDirExec: <"+dir.getAbsolutePath()+
">: Always executable");
1071 final long t0 = debug ? System.currentTimeMillis() : 0;
1072 final File exeTestFile;
1073 String exeNativePath;
1074 final boolean existingExe;
1076 final File permExeTestFile = DEBUG_EXE_EXISTING_FILE ?
new File(dir,
"jogamp_exe_tst"+getExeTestFileSuffix()) :
null;
1077 if(
null != permExeTestFile && permExeTestFile.exists() ) {
1078 exeTestFile = permExeTestFile;
1081 exeTestFile = File.createTempFile(
"jogamp_exe_tst", getExeTestFileSuffix(), dir);
1082 existingExe =
false;
1083 fillExeTestFile(exeTestFile);
1085 exeNativePath = getExeNativePath( exeTestFile.getCanonicalPath() );
1086 }
catch (
final SecurityException se) {
1088 }
catch (
final IOException e) {
1090 e.printStackTrace();
1094 final long t1 = debug ? System.currentTimeMillis() : 0;
1098 Boolean isNioExec =
null;
1099 if( existingExe || exeTestFile.setExecutable(
true ,
true ) ) {
1100 t2 = debug ? System.currentTimeMillis() : 0;
1102 isNioExec = isNioExecutableFile(exeTestFile);
1103 if(
null != isNioExec ) {
1104 res = isNioExec.booleanValue() ? 0 : -1;
1106 if(
null == isNioExec || 0 <= res ) {
1114 pr = Runtime.getRuntime().exec( getExeTestCommandArgs( exeNativePath ),
null,
null );
1115 if( DEBUG_EXE && !DEBUG_EXE_NOSTREAM ) {
1116 new StreamMonitor(
new InputStream[] { pr.getInputStream(), pr.getErrorStream() }, System.err,
"Exe-Tst: ");
1119 exitValue = pr.exitValue();
1120 if( 0 == exitValue ) {
1125 }
catch (
final SecurityException se) {
1127 }
catch (
final Throwable t) {
1128 t2 = debug ? System.currentTimeMillis() : 0;
1131 System.err.println(
"IOUtil.testDirExec: <"+exeNativePath+
">: Caught "+t.getClass().getSimpleName()+
": "+t.getMessage());
1132 t.printStackTrace();
1141 }
catch (
final Throwable t) {
1148 t2 = debug ? System.currentTimeMillis() : 0;
1151 final boolean ok = 0 <= res;
1152 if( !DEBUG_EXE && !existingExe ) {
1153 exeTestFile.delete();
1156 final long t3 = System.currentTimeMillis();
1157 System.err.println(
"IOUtil.testDirExec(): test-exe <"+exeNativePath+
">, existingFile "+existingExe+
", isNioExec "+isNioExec+
", returned "+exitValue);
1158 System.err.println(
"IOUtil.testDirExec(): abs-path <"+dir.getAbsolutePath()+
">: res "+res+
" -> "+ok);
1159 System.err.println(
"IOUtil.testDirExec(): total "+(t3-t0)+
"ms, create "+(t1-t0)+
"ms, fill "+(t2-t1)+
"ms, execute "+(t3-t2)+
"ms");
1164 private static File testDirImpl(
final File dir,
final boolean create,
final boolean executable,
final String dbgMsg)
1165 throws SecurityException
1168 if (create && !dir.exists()) {
1174 res =
testFile(dir,
true,
true) ? dir :
null;
1177 System.err.println(
"IOUtil.testDirImpl("+dbgMsg+
"): <"+dir.getAbsolutePath()+
">, create "+create+
", exec "+executable+
": "+(
null != res));
1196 public static File
testDir(
final File dir,
final boolean create,
final boolean executable)
1197 throws SecurityException
1199 return testDirImpl(dir, create, executable,
"testDir");
1202 private static boolean isStringSet(
final String s) {
return null != s && 0 < s.length(); }
1228 private static File getSubTempDir(
final File tmpRoot,
final String tmpSubDirPrefix,
final boolean executable,
final String dbgMsg)
1229 throws SecurityException
1231 File tmpBaseDir =
null;
1232 if(
null != testDirImpl(tmpRoot,
true , executable, dbgMsg)) {
1233 for(
int i = 0;
null == tmpBaseDir && i<=9999; i++) {
1234 final String tmpDirSuffix = String.format((Locale)
null,
"_%04d", i);
1235 tmpBaseDir = testDirImpl(
new File(tmpRoot, tmpSubDirPrefix+tmpDirSuffix),
true , executable, dbgMsg);
1241 private static File getFile(
final String fname) {
1242 if( isStringSet(fname) ) {
1243 return new File(fname);
1276 throws SecurityException, IOException
1279 synchronized(
IOUtil.class) {
1283 final File ctxTempDir = AndroidUtils.getTempRoot();
1284 if(
null != ctxTempDir) {
1285 tempRootNoexec = getSubTempDir(ctxTempDir,
tmpSubDir,
false ,
"Android.ctxTemp");
1286 tempRootExec = tempRootNoexec;
1287 return tempRootExec;
1293 System.err.println(
"IOUtil.getTempRoot(): tempX1 <"+java_io_tmpdir+
">, used "+(
null!=java_io_tmpdir));
1296 final File user_tmpdir;
1298 String __user_tmpdir = System.getenv(
"TMPDIR");
1299 if( !isStringSet(__user_tmpdir) ) {
1300 __user_tmpdir = System.getenv(
"TEMP");
1302 final File _user_tmpdir = getFile(__user_tmpdir);
1303 if(
null != _user_tmpdir && !_user_tmpdir.equals(java_io_tmpdir) ) {
1304 user_tmpdir = _user_tmpdir;
1309 System.err.println(
"IOUtil.getTempRoot(): tempX3 <"+_user_tmpdir+
">, used "+(
null!=user_tmpdir));
1315 System.err.println(
"IOUtil.getTempRoot(): tempX4 <"+user_home+
">, used "+(
null!=user_home));
1318 final File xdg_cache_home;
1320 String __xdg_cache_home;
1321 if( getOSHasFreeDesktopXDG() ) {
1322 __xdg_cache_home = System.getenv(XDG_CACHE_HOME_envkey);
1323 if( !isStringSet(__xdg_cache_home) &&
null != user_home ) {
1324 __xdg_cache_home = user_home.getAbsolutePath() + File.separator +
".cache" ;
1327 __xdg_cache_home =
null;
1329 final File _xdg_cache_home = getFile(__xdg_cache_home);
1330 if(
null != _xdg_cache_home && !_xdg_cache_home.equals(java_io_tmpdir) ) {
1331 xdg_cache_home = _xdg_cache_home;
1333 xdg_cache_home =
null;
1336 System.err.println(
"IOUtil.getTempRoot(): tempX2 <"+_xdg_cache_home+
">, used "+(
null!=xdg_cache_home));
1341 if(
null == tempRootExec &&
null != java_io_tmpdir ) {
1345 tempRootExec = getSubTempDir(java_io_tmpdir,
tmpSubDir,
false ,
"tempX1");
1347 tempRootExec = getSubTempDir(java_io_tmpdir,
tmpSubDir,
true ,
"tempX1");
1352 if(
null == tempRootExec &&
null != xdg_cache_home ) {
1353 tempRootExec = getSubTempDir(xdg_cache_home,
tmpSubDir,
true ,
"tempX2");
1357 if(
null == tempRootExec &&
null != user_tmpdir ) {
1358 tempRootExec = getSubTempDir(user_tmpdir,
tmpSubDir,
true ,
"tempX3");
1362 if(
null == tempRootExec &&
null != user_home ) {
1363 tempRootExec = getSubTempDir(user_home,
"." +
tmpSubDir,
true ,
"tempX4");
1366 if(
null != tempRootExec ) {
1367 tempRootNoexec = tempRootExec;
1370 if(
null == tempRootNoexec &&
null != java_io_tmpdir ) {
1371 tempRootNoexec = getSubTempDir(java_io_tmpdir,
tmpSubDir,
false ,
"temp01");
1375 if(
null == tempRootNoexec &&
null != xdg_cache_home ) {
1376 tempRootNoexec = getSubTempDir(xdg_cache_home,
tmpSubDir,
false ,
"temp02");
1380 if(
null == tempRootNoexec &&
null != user_tmpdir ) {
1381 tempRootNoexec = getSubTempDir(user_tmpdir,
tmpSubDir,
false ,
"temp03");
1385 if(
null == tempRootNoexec &&
null != user_home ) {
1386 tempRootNoexec = getSubTempDir(user_home,
"." +
tmpSubDir,
false ,
"temp04");
1391 final String tempRootExecAbsPath =
null != tempRootExec ? tempRootExec.getAbsolutePath() :
null;
1392 final String tempRootNoexecAbsPath =
null != tempRootNoexec ? tempRootNoexec.getAbsolutePath() :
null;
1393 System.err.println(
"IOUtil.getTempRoot(): temp dirs: exec: "+tempRootExecAbsPath+
", noexec: "+tempRootNoexecAbsPath);
1398 final File r = executable ? tempRootExec : tempRootNoexec ;
1400 final String exe_s = executable ?
"executable " :
"";
1401 throw new IOException(
"Could not determine a temporary "+exe_s+
"directory");
1403 final FilePermission fp =
new FilePermission(r.getAbsolutePath(),
"read,write,delete");
1407 private static File tempRootExec =
null;
1408 private static File tempRootNoexec =
null;
1409 private static volatile boolean tempRootSet =
false;
1428 public static File
createTempFile(
final String prefix,
final String suffix,
final boolean executable)
1429 throws IllegalArgumentException, IOException, SecurityException
1431 return File.createTempFile( prefix, suffix,
getTempDir(executable) );
1434 public static void close(
final Closeable stream,
final boolean throwRuntimeException)
throws RuntimeException {
1435 if(
null != stream) {
1438 }
catch (
final IOException e) {
1439 if(throwRuntimeException) {
1440 throw new RuntimeException(e);
1442 System.err.println(
"Caught Exception: ");
1443 e.printStackTrace();
1457 public static IOException
close(
final Closeable stream,
final IOException[] saveOneIfFree,
final PrintStream dumpExcess) {
1460 }
catch(
final IOException e) {
1461 if(
null == saveOneIfFree[0] ) {
1462 saveOneIfFree[0] = e;
1464 if(
null != dumpExcess ) {
1465 dumpExcess.println(
"Caught "+e.getClass().getSimpleName()+
": "+e.getMessage());
1466 e.printStackTrace(dumpExcess);
1481 public static ArrayList<String>
filesOf(
final List<String> paths,
final List<Pattern> excludes,
final List<Pattern> includes) {
1482 final ArrayList<String> files =
new ArrayList<String>(paths.size()*32);
1483 final ArrayList<String> todo =
new ArrayList<String>(paths);
1484 while(todo.size() > 0) {
1485 final String p = todo.remove(0);
1486 if(
null != excludes && excludes.size() > 0) {
1487 boolean exclude =
false;
1488 for(
int i=0; !exclude && i<excludes.size(); i++) {
1489 exclude = excludes.get(i).matcher(p).matches();
1492 System.err.println(
"IOUtil.filesOf(): excluding <"+p+
"> (exclude["+i+
"]: "+excludes.get(i)+
")");
1500 final File f =
new File(p);
1503 System.err.println(
"IOUtil.filesOf(): not existing: "+f);
1506 }
else if( f.isDirectory() ) {
1507 final String[] subs = f.list();
1508 if(
null == subs ) {
1510 System.err.println(
"IOUtil.filesOf(): null list of directory: "+f);
1512 }
else if( 0 == subs.length ) {
1514 System.err.println(
"IOUtil.filesOf(): empty list of directory: "+f);
1518 final String pp = p.endsWith(
"/") ? p : p+
"/";
1519 for(
int i=0; i<subs.length; i++) {
1520 todo.add(j++, pp+subs[i]);
1524 if(
null != includes && includes.size() > 0) {
1525 boolean include =
false;
1526 for(
int i=0; !include && i<includes.size(); i++) {
1527 include = includes.get(i).matcher(p).matches();
1530 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 boolean testExeFile(final File file)
Test whether executable file exists, no OS executable tests performed, just permissions via Java.
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...