litesoft
@ 939
litesoft / trunk / Java / ScarPlus / src / com / esotericsoftware / scar / Utils.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 |
package com.esotericsoftware.scar; import java.io.*; import java.net.*; import org.litesoft.core.typeutils.Objects; import java.util.*; import java.util.regex.*; import javax.tools.*; import com.esotericsoftware.utils.*; @SuppressWarnings("UnusedDeclaration") public class Utils extends FileUtil { /** * The Scar installation directory. The value comes from the SCAR_HOME environment variable, if it exists. Alternatively, the * "scar.home" System property can be defined. */ static public final String SCAR_HOME; static { if ( System.getProperty( "scar.home" ) != null ) { SCAR_HOME = System.getProperty( "scar.home" ); } else { SCAR_HOME = System.getenv( "SCAR_HOME" ); } } /** * The Java installation directory. */ static public final String JAVA_HOME = System.getProperty( "java.home" ); /** * Returns the full path for the specified file name in the current working directory, the {@link #SCAR_HOME}, and the bin * directory of {@link #JAVA_HOME}. */ static public String resolvePath( String fileName ) { if ( fileName == null ) { return null; } String foundFile = lowLevelResolve( fileName ); LOGGER.trace.log( "Path \"", fileName, "\" resolved to: ", foundFile ); return foundFile; } private static String lowLevelResolve( String fileName ) { String foundFile; if ( fileExists( foundFile = canonical( fileName ) ) ) { return foundFile; } if ( fileExists( foundFile = new File( SCAR_HOME, fileName ).getPath() ) ) { return foundFile; } if ( fileExists( foundFile = new File( JAVA_HOME, "bin/" + fileName ).getPath() ) ) { return foundFile; } return fileName; } static public File findCommonDirPathFromCanonicalDirPaths( File pPath1, File pPath2 ) { String zPath1 = pPath1.getPath(); String zPath2 = pPath2.getPath(); if (zPath2.startsWith(zPath1)) // Check the Happy Cases { return pPath1; } if (zPath1.startsWith(zPath2)) { return pPath2; } String zSharedPath = findSharedPath( zPath1, zPath2 ); if ( zSharedPath.length() != 0 ) { for ( File zShared = new File( zSharedPath ); zShared != null; zShared = zShared.getParentFile() ) { if ( zShared.isDirectory() ) { return zShared; } } } return null; } static private String findSharedPath( String pPath1, String pPath2 ) { int zLength = Math.min(pPath1.length(), pPath2.length()); if ( (zLength == 0) || (pPath1.charAt(0) != pPath2.charAt(0)) ) { return ""; } for (int i = 1; i < zLength; i++) { if ( pPath1.charAt( i ) != pPath2.charAt( i ) ) { return pPath1.substring( 0, i ); // i == Exclusive } } return pPath1.substring( 0, zLength ); } /** * Returns the canonical path for the specified path. Eg, if "." is passed, this will resolve the actual path and return it. */ static public String canonical( String path ) { path = assertNotEmpty( "path", path ); File file = new File( path ); try { return file.getCanonicalPath(); } catch ( IOException ex ) { file = file.getAbsoluteFile(); if ( file.getName().equals( "." ) ) { file = file.getParentFile(); } return file.getPath(); } } /** * Returns the canonical path for the specified path. Eg, if "." is passed, this will resolve the actual path and return it. */ static public File canonical( File path ) { assertNotNull( "path", path ); try { return path.getCanonicalFile(); } catch ( IOException ex ) { return path.getAbsoluteFile(); } } /** * Returns true if the file exists. */ static public boolean fileExists( String path ) { return new File( assertNotEmpty( "path", path ) ).exists(); } /** * Returns only the filename portion of the specified path. */ static public String fileName( String path ) { return new File( canonical( path ) ).getName(); } /** * Returns the parent directory of the specified path. */ static public String parent( String path ) { return new File( canonical( path ) ).getParent(); } /** * Returns only the extension portion of the specified path, or an empty string if there is no extension. */ static public String fileExtension( String file ) { file = assertNotEmpty( "file", file ); int commaIndex = file.indexOf( '.' ); return (commaIndex == -1) ? "" : file.substring( commaIndex + 1 ); } /** * Returns only the filename portion of the specified path, without the extension, if any. */ static public String fileWithoutExtension( String file ) { file = assertNotEmpty( "file", file ); int commaIndex = file.indexOf( '.' ); if ( commaIndex == -1 ) { commaIndex = file.length(); } int slashIndex = file.replace( '\\', '/' ).lastIndexOf( '/' ); if ( slashIndex == -1 ) { slashIndex = 0; } else { slashIndex++; } return file.substring( slashIndex, commaIndex ); } /** * Returns a substring of the specified text. * * @param end The end index of the substring. If negative, the index used will be "text.length() + end". */ static public String substring( String text, int start, int end ) { assertNotNull( "text", text ); assertNotNegative( "start", start ); return text.substring( start, (end >= 0) ? end : text.length() + end ); } /** * Splits the specified command at spaces that are not surrounded by quotes and passes the result to {@link #shell(String...)}. */ static public void shell( String command ) { List<String> matchList = new ArrayList<String>(); Pattern regex = Pattern.compile( "[^\\s\"']+|\"([^\"]*)\"|'([^']*)'" ); Matcher regexMatcher = regex.matcher( command ); while ( regexMatcher.find() ) { if ( regexMatcher.group( 1 ) != null ) { matchList.add( regexMatcher.group( 1 ) ); } else if ( regexMatcher.group( 2 ) != null ) { matchList.add( regexMatcher.group( 2 ) ); } else { matchList.add( regexMatcher.group() ); } } shell( matchList.toArray( new String[matchList.size()] ) ); } /** * Executes the specified shell command. {@link #resolvePath(String)} is used to locate the file to execute. If not found, on * Windows the same filename with an "exe" extension is also tried. */ static public void shell( String... command ) { assertNotEmpty( "command", command ); String originalCommand = (command[0] = assertNotEmpty( "shell Command", command[0] )); command[0] = resolvePath( command[0] ); if ( !fileExists( command[0] ) && isWindows ) { command[0] = resolvePath( command[0] + ".exe" ); if ( !fileExists( command[0] ) ) { command[0] = originalCommand; } } if ( LOGGER.trace.isEnabled() ) { StringBuilder buffer = new StringBuilder( 256 ); for ( String text : command ) { if ( text.contains( " " ) ) { buffer.append( '"' ); buffer.append( text ); buffer.append( '"' ); } else { buffer.append( text ); } buffer.append( ' ' ); } LOGGER.trace.log( "Executing command: ", buffer ); } try { Process process = new ProcessBuilder( command ).start(); Thread zOut = new CopyOutputThread( process.getInputStream(), System.out ); Thread zErr = new CopyOutputThread( process.getErrorStream(), System.err ); zOut.join(); zErr.join(); // try { // process.waitFor(); // } catch (InterruptedException ignored) { // } if ( process.exitValue() != 0 ) { StringBuilder buffer = new StringBuilder( 256 ); for ( String text : command ) { buffer.append( text ); buffer.append( ' ' ); } throw new RuntimeException( "Error (" + process.exitValue() + ") executing command: " + buffer ); } } catch ( IOException e ) { throw new WrappedIOException( e ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } } /** * Creates a new keystore for signing JARs. If the keystore file already exists, no action will be taken. * * @return The path to the keystore file. */ static public String keystore( String keystoreFile, String alias, String password, String company, String title ) { if ( fileExists( keystoreFile = assertNotEmpty( "keystoreFile", keystoreFile ) ) ) { return keystoreFile; } alias = assertNotEmpty( "alias", alias ); company = assertNotEmpty( "company", company ); title = assertNotEmpty( "title", title ); if ( (password = assertNotEmpty( "password", password )).length() < 6 ) { throw new IllegalArgumentException( "password must be 6 or more characters." ); } LOGGER.debug.log( "Creating keystore (", alias, ":", password, ", ", company, ", ", title, "): ", keystoreFile ); File file = new File( keystoreFile ); //noinspection ResultOfMethodCallIgnored file.delete(); Process process; try { process = Runtime.getRuntime().exec( new String[]{resolvePath( "keytool" ), "-genkey", "-keystore", keystoreFile, "-alias", alias} ); OutputStreamWriter writer = new OutputStreamWriter( process.getOutputStream() ); writer.write( password + "\n" ); // Enter keystore password: writer.write( password + "\n" ); // Re-enter new password: writer.write( company + "\n" ); // What is your first and last name? writer.write( title + "\n" ); // What is the name of your organizational unit? writer.write( title + "\n" ); // What is the name of your organization? writer.write( "\n" ); // What is the name of your City or Locality? [Unknown] writer.write( "\n" ); // What is the name of your State or Province? [Unknown] writer.write( "\n" ); // What is the two-letter country code for this unit? [Unknown] writer.write( "yes\n" ); // Correct? writer.write( "\n" ); // Return if same alias key password as keystore. writer.flush(); process.getOutputStream().close(); process.getInputStream().close(); process.getErrorStream().close(); } catch ( IOException e ) { throw new WrappedIOException( e ); } try { process.waitFor(); } catch ( InterruptedException ignored ) { } if ( !file.exists() ) { throw new RuntimeException( "Error creating keystore." ); } return keystoreFile; } public static Class compileDynamicCodeToClass( int pOverheadStartLines, final String pCode, final URL... pClasspathURLs ) throws ClassNotFoundException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if ( compiler == null ) { throw new RuntimeException( "No compiler available. Ensure you are running from a 1.6+ JDK, and not a JRE." ); } final ByteArrayOutputStream output = new ByteArrayOutputStream( 32 * 1024 ); final SimpleJavaFileObject javaObject = new SimpleJavaFileObject( URI.create( "Generated.java" ), JavaFileObject.Kind.SOURCE ) { @Override public OutputStream openOutputStream() { return output; } @Override public CharSequence getCharContent( boolean ignoreEncodingErrors ) { return pCode; } }; DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); //noinspection unchecked compiler.getTask( null, new ForwardingJavaFileManager( compiler.getStandardFileManager( null, null, null ) ) { @Override public JavaFileObject getJavaFileForOutput( Location location, String className, JavaFileObject.Kind kind, FileObject sibling ) { return javaObject; } }, diagnostics, null, null, Arrays.asList( javaObject ) ).call(); if ( !diagnostics.getDiagnostics().isEmpty() ) { StringBuilder buffer = new StringBuilder( 1024 ); for ( Diagnostic diagnostic : diagnostics.getDiagnostics() ) { if ( buffer.length() > 0 ) { buffer.append( "\n" ); } buffer.append( "Line " ); buffer.append( diagnostic.getLineNumber() - pOverheadStartLines ); buffer.append( ": " ); buffer.append( diagnostic.getMessage( null ).replaceAll( "^Generated.java:\\d+:\\d* ", "" ) ); } throw new RuntimeException( "Compilation errors:\n" + buffer ); } // Load class. return new URLClassLoader( pClasspathURLs, Scar.class.getClassLoader() ) { @Override protected synchronized Class<?> loadClass( String name, boolean resolve ) throws ClassNotFoundException { // Look in this classloader before the parent. Class c = findLoadedClass( name ); if ( c == null ) { try { c = findClass( name ); } catch ( ClassNotFoundException e ) { return super.loadClass( name, resolve ); } } if ( resolve ) { resolveClass( c ); } return c; } @Override protected Class<?> findClass( String name ) throws ClassNotFoundException { if ( name.equals( "Generated" ) ) { byte[] bytes = output.toByteArray(); return defineClass( name, bytes, 0, bytes.length ); } return super.findClass( name ); } }.loadClass( "Generated" ); } } |
Commits for litesoft/trunk/Java/ScarPlus/src/com/esotericsoftware/scar/Utils.java
Revision | Author | Commited | Message |
---|---|---|---|
939 Diff | GeorgeS | Mon 02 Jun, 2014 21:30:31 +0000 | Extracting commonfoundation |
889 Diff | GeorgeS | Tue 18 Dec, 2012 00:21:56 +0000 | Correct Relative Path for JARing |
361 Diff | GeorgeS | Mon 08 Aug, 2011 01:34:17 +0000 | |
315 Diff | GeorgeS | Sun 17 Jul, 2011 15:48:36 +0000 | |
314 Diff | GeorgeS | Fri 15 Jul, 2011 01:01:49 +0000 | |
300 Diff | GeorgeS | Thu 07 Jul, 2011 00:30:55 +0000 | |
299 Diff | GeorgeS | Tue 05 Jul, 2011 04:45:50 +0000 | |
298 Diff | GeorgeS | Fri 01 Jul, 2011 00:25:50 +0000 | |
287 Diff | GeorgeS | Mon 20 Jun, 2011 06:24:24 +0000 | |
182 | GeorgeS | Sat 23 Apr, 2011 00:19:10 +0000 |