// Private since we can't add a vtable slot in 4.1.x. private void exitNoChecks(int status) { if (runShutdownHooks()) exitInternal(status); // Someone else already called runShutdownHooks(). // Make sure we are not/no longer in the shutdownHooks set. // And wait till the thread that is calling runShutdownHooks() finishes. synchronized (libpath) { if (shutdownHooks != null) { shutdownHooks.remove(Thread.currentThread()); // Interrupt the exit sequence thread, in case it was waiting // inside a join on our thread. exitSequence.interrupt(); // Shutdown hooks are still running, so we clear status to // make sure we don't halt. status = 0; } } // If exit() is called again after the shutdown hooks have run, but // while finalization for exit is going on and the status is non-zero // we halt immediately. if (status != 0) exitInternal(status); while (true) try { exitSequence.join(); } catch (InterruptedException e) { // Ignore, we've suspended indefinitely to let all shutdown // hooks complete, and to let any non-zero exits through, because // this is a duplicate call to exit(0). } }
protected LockStatus lock(final String sessionId, final long timeout, final TimeUnit timeUnit) { if (_log.isDebugEnabled()) { _log.debug("Locking session " + sessionId); } final long start = System.currentTimeMillis(); try { acquireLock( sessionId, LOCK_RETRY_INTERVAL, LOCK_MAX_RETRY_INTERVAL, timeUnit.toMillis(timeout), System.currentTimeMillis()); _stats.registerSince(ACQUIRE_LOCK, start); if (_log.isDebugEnabled()) { _log.debug("Locked session " + sessionId); } return LockStatus.LOCKED; } catch (final TimeoutException e) { _log.warn( "Reached timeout when trying to aquire lock for session " + sessionId + ". Will use this session without this lock."); _stats.registerSince(ACQUIRE_LOCK_FAILURE, start); return LockStatus.COULD_NOT_AQUIRE_LOCK; } catch (final InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Got interrupted while trying to lock session.", e); } catch (final ExecutionException e) { _log.warn("An exception occurred when trying to aquire lock for session " + sessionId); _stats.registerSince(ACQUIRE_LOCK_FAILURE, start); return LockStatus.COULD_NOT_AQUIRE_LOCK; } }
public SurefireProvider createProvider(boolean isInsideFork) { ClassLoader systemClassLoader = java.lang.Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(classLoader); StartupConfiguration starterConfiguration = startupConfiguration; // Note: Duplicated in ForkedBooter#createProviderInCurrentClassloader final Object o = surefireReflector.createBooterConfiguration( classLoader, reporterManagerFactory, isInsideFork); surefireReflector.setTestSuiteDefinitionAware( o, providerConfiguration.getTestSuiteDefinition()); surefireReflector.setProviderPropertiesAware(o, providerConfiguration.getProviderProperties()); surefireReflector.setReporterConfigurationAware( o, providerConfiguration.getReporterConfiguration()); surefireReflector.setTestClassLoaderAware(o, classLoader); surefireReflector.setTestArtifactInfoAware(o, providerConfiguration.getTestArtifact()); surefireReflector.setRunOrderParameters(o, providerConfiguration.getRunOrderParameters()); surefireReflector.setIfDirScannerAware(o, providerConfiguration.getDirScannerParams()); Object provider = surefireReflector.instantiateProvider(starterConfiguration.getActualClassName(), o); Thread.currentThread().setContextClassLoader(systemClassLoader); return new ProviderProxy(provider, classLoader); }
public void run() { System.out.println("System has entered running mode"); while (threadCheck) { System.out.println("O.K. see how we execute target program"); this.generatePdf(); try { System.out.println("Right, let's wait for task to complete of fail"); java.lang.Thread.currentThread().sleep(200); System.out.println("It's time for us threads to get back to work after the nap"); } catch (java.lang.InterruptedException IntExec) { System.out.println(IntExec.getMessage()); } threadCheck = false; System.out.println("We shall be lucky to get back to start in one piece"); } if (!threadCheck) { Thread.currentThread().stop(); } }
public bgldynamic get() { Thread t = java.lang.Thread.currentThread(); if (t instanceof bglpthread) { return ((bglpthread) t).env; } else { return bigloo.bgldynamic.current_dynamic_env; } }
/** * On first invocation, run all the shutdown hooks and return true. Any subsequent invocations * will simply return false. Note that it is package accessible so that VMRuntime can call it when * VM exit is not triggered by a call to Runtime.exit(). * * @return was the current thread the first one to call this method? */ boolean runShutdownHooks() { boolean first = false; synchronized (libpath) // Synch on libpath, not this, to avoid deadlock. { if (exitSequence == null) { first = true; exitSequence = Thread.currentThread(); if (shutdownHooks != null) { Iterator i = shutdownHooks.iterator(); while (i.hasNext()) // Start all shutdown hooks. try { ((Thread) i.next()).start(); } catch (IllegalThreadStateException e) { i.remove(); } } } } if (first) { if (shutdownHooks != null) { // Check progress of all shutdown hooks. As a hook completes, // remove it from the set. If a hook calls exit, it removes // itself from the set, then waits indefinitely on the // exitSequence thread. Once the set is empty, set it to null to // signal all finalizer threads that halt may be called. while (true) { Thread[] hooks; synchronized (libpath) { hooks = new Thread[shutdownHooks.size()]; shutdownHooks.toArray(hooks); } if (hooks.length == 0) break; for (int i = 0; i < hooks.length; i++) { try { synchronized (libpath) { if (!shutdownHooks.contains(hooks[i])) continue; } hooks[i].join(); synchronized (libpath) { shutdownHooks.remove(hooks[i]); } } catch (InterruptedException x) { // continue waiting on the next thread } } } synchronized (libpath) { shutdownHooks = null; } } // Run finalization on all finalizable objects (even if they are // still reachable). runFinalizationForExit(); } return first; }
/** Creates a new instance of TestLoad */ public static void main(String[] args) { try { while (true) { TestLoad test = new TestLoad(args); test.start(); Thread.currentThread().sleep(CREATE_DELAY); } } catch (InterruptedException ex) { ex.printStackTrace(); } }
@Override public void run() { while (true) { closeUnusedWebdrivers(); try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } } }
@Override public void run() { int i = 0; while (i < 4) { try { Thread.sleep(500); System.out.println("Je suis : " + Thread.currentThread().getName()); } catch (InterruptedException ie) { System.out.println("Nous avons un problème"); } i++; } }
/** * Resets {@link Locale#getDefault()} to what it was when {@link #setDefault(Locale)} was called. * Should be called after you're done with using {@link Locale#getDefault()}. * * @return the default {@link Locale} that was set * @throws IllegalStateException if this thread wasn't the last one to successfully call {@link * #setDefault(Locale)} */ public static Locale resetDefaultLocale() { checkState( LOCK.isHeldByCurrentThread(), "Current thread: %s may not unlock: %s", Thread.currentThread().getName(), LOCK); try { Locale.setDefault(defaultLocale); return defaultLocale; } finally { LOCK.unlock(); } }
@Override public void execute() { Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); Integer divisor = rand.nextInt(100); System.out.println("Request Read by Thread id=" + Thread.currentThread().getId()); try { transactionQueue.put(divisor); Thread.sleep(100); } catch (InterruptedException e) { } }
public void waitFor(E message) { synchronized (message) { assert !reservedMessages.containsKey(message) : "Thread '" + reservedMessages.get(message) + "' already reserved this message"; reservedMessages.put(message, java.lang.Thread.currentThread()); while (!sentMessages.contains(message)) { try { message.wait(); } catch (InterruptedException ex) { throw new InterruptedExceptionRuntimeException(ex); } } } }
@Override public void execute() { try { Integer divisor = transactionQueue.take(); // Here we simulate processing a transaction by dividing a random number with another that // can // sometimes be 0 int result = this.transactionId / divisor; updatePeers(this.processId, this.transactionId); lastTransaction = this.transactionId; System.out.println( "Transaction #" + this.transactionId.toString() + " Processed: Result=" + result + ", Divisor=" + divisor + ", Thread Id=" + Thread.currentThread().getId()); Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
@BeforeClass public static void setup() throws InterruptedException, IOException { LOG.info("Starting up YARN cluster"); conf = StramClientUtils.addDTDefaultResources(conf); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 64); conf.setInt( "yarn.nodemanager.vmem-pmem-ratio", 20); // workaround to avoid containers being killed because java allocated too much vmem conf.setStrings("yarn.scheduler.capacity.root.queues", "default"); conf.setStrings("yarn.scheduler.capacity.root.default.capacity", "100"); StringBuilder adminEnv = new StringBuilder(1024); if (System.getenv("JAVA_HOME") == null) { adminEnv.append("JAVA_HOME=").append(System.getProperty("java.home")); adminEnv.append(","); } adminEnv.append("MALLOC_ARENA_MAX=4"); // see MAPREDUCE-3068, MAPREDUCE-3065 adminEnv.append(","); adminEnv.append("CLASSPATH=").append(getTestRuntimeClasspath()); conf.set(YarnConfiguration.NM_ADMIN_USER_ENV, adminEnv.toString()); if (yarnCluster == null) { yarnCluster = new MiniYARNCluster(StramMiniClusterTest.class.getName(), 1, 1, 1); yarnCluster.init(conf); yarnCluster.start(); } conf = yarnCluster.getConfig(); URL url = Thread.currentThread().getContextClassLoader().getResource("yarn-site.xml"); if (url == null) { LOG.error("Could not find 'yarn-site.xml' dummy file in classpath"); throw new RuntimeException("Could not find 'yarn-site.xml' dummy file in classpath"); } File confFile = new File(url.getPath()); yarnCluster.getConfig().set("yarn.application.classpath", confFile.getParent()); OutputStream os = new FileOutputStream(confFile); LOG.debug("Conf file: {}", confFile); yarnCluster.getConfig().writeXml(os); os.close(); try { Thread.sleep(2000); } catch (InterruptedException e) { LOG.info("setup thread sleep interrupted. message=" + e.getMessage()); } }
private void processInteractiveMode(ShellMethods curShell) { Scanner inputScanner = new Scanner(System.in); while (!Thread.currentThread().isInterrupted()) { System.out.print(curShell.getCurrentDirectory() + "$ "); String instructions = inputScanner.nextLine(); try { doInstructions(instructions, curShell); } catch (IOException catchedException) { System.err.println(catchedException.getMessage()); } catch (ShellInterruptionException catchedException) { return; } } }
@Override public Page getNextPage() { if (isFinished()) { return null; } if (pageProcessingDelayInMillis > 0) { try { sleep(pageProcessingDelayInMillis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } } return super.getNextPage(); }
public boolean search() { Thread tread = java.lang.Thread.currentThread(); java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean(); long startCPU = b.getThreadCpuTime(tread.getId()); long startUser = b.getThreadUserTime(tread.getId()); boolean result = store.consistency(); System.out.println("*** consistency = " + result); Search<SetVar> label = new DepthFirstSearch<SetVar>(); SelectChoicePoint<SetVar> select = new SimpleSelect<SetVar>( vars.toArray(new SetVar[vars.size()]), new MinLubCard<SetVar>(), new MaxGlbCard<SetVar>(), new IndomainSetMin<SetVar>()); // label.setSolutionListener(new SetSimpleSolutionListener<SetVar>()); label.getSolutionListener().searchAll(false); label.getSolutionListener().recordSolutions(false); result = label.labeling(store, select); if (result) { System.out.println("*** Yes"); for (int i = 0; i < weeks; i++) { for (int j = 0; j < groups; j++) { System.out.print(golferGroup[i][j].dom() + " "); } System.out.println(); } } else System.out.println("*** No"); System.out.println( "ThreadCpuTime = " + (b.getThreadCpuTime(tread.getId()) - startCPU) / (long) 1e+6 + "ms"); System.out.println( "ThreadUserTime = " + (b.getThreadUserTime(tread.getId()) - startUser) / (long) 1e+6 + "ms"); return result; }
private static String getTestRuntimeClasspath() { InputStream classpathFileStream = null; BufferedReader reader = null; String envClassPath = ""; LOG.info("Trying to generate classpath for app master from current thread's classpath"); try { // Create classpath from generated classpath // Check maven pom.xml for generated classpath info // Works in tests where compile time env is same as runtime. ClassLoader thisClassLoader = Thread.currentThread().getContextClassLoader(); String generatedClasspathFile = "mvn-generated-classpath"; classpathFileStream = thisClassLoader.getResourceAsStream(generatedClasspathFile); if (classpathFileStream == null) { LOG.info("Could not load classpath resource " + generatedClasspathFile); return envClassPath; } LOG.info("Readable bytes from stream=" + classpathFileStream.available()); reader = new BufferedReader(new InputStreamReader(classpathFileStream)); String cp = reader.readLine(); if (cp != null) { envClassPath += cp.trim() + ":"; } // Put the file itself on classpath for tasks. envClassPath += thisClassLoader.getResource(generatedClasspathFile).getFile(); } catch (IOException e) { LOG.info( "Could not find the necessary resource to generate class path for tests. Error=" + e.getMessage()); } try { if (classpathFileStream != null) { classpathFileStream.close(); } if (reader != null) { reader.close(); } } catch (IOException e) { LOG.info("Failed to close class path file stream or reader. Error=" + e.getMessage()); } return envClassPath; }
/** * It parses the provided file and parsing parameters followed by problem solving. * * @param args parameters describing the flatzinc file containing the problem to be solved as well * as options for problem solving. * <p>TODO what are the conditions for different exceptions being thrown? Write little info * below. * @throws ParseException * @throws TokenMgrError */ public static void main(String[] args) { Options opt = new Options(args); if (opt.getVerbose()) System.out.println("Flatzinc2JaCoP: compiling and executing " + args[args.length - 1]); Thread tread = java.lang.Thread.currentThread(); java.lang.management.ThreadMXBean b = java.lang.management.ManagementFactory.getThreadMXBean(); long startCPU = b.getThreadCpuTime(tread.getId()); Parser parser = new Parser(opt.getFile()); parser.setOptions(opt); try { parser.model(); } catch (FailException e) { System.err.println( "=====UNSATISFIABLE====="); // "*** Evaluation of model resulted in fail."); } catch (ArithmeticException e) { System.err.println("*** Evaluation of model resulted in integer overflow."); } catch (ParseException e) { System.out.println("*** Parser exception " + e); } catch (TokenMgrError e) { System.out.println("*** Parser exception " + e); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("*** Array out of bound exception " + e); } catch (OutOfMemoryError e) { System.out.println("*** Out of memory error; consider option -Xmx... for JVM"); } catch (StackOverflowError e) { System.out.println("*** Stack overflow exception error; consider option -Xss... for JVM"); } if (opt.getStatistics()) { System.out.println( "\nTotal CPU time : " + (b.getThreadCpuTime(tread.getId()) - startCPU) / (long) 1e+6 + "ms"); } }
private static void finalizerTimedOut(Object object) { // The current object has exceeded the finalization deadline; abort! String message = object.getClass().getName() + ".finalize() timed out after " + (MAX_FINALIZE_NANOS / NANOS_PER_SECOND) + " seconds"; Exception syntheticException = new TimeoutException(message); // We use the stack from where finalize() was running to show where it was stuck. syntheticException.setStackTrace(FinalizerDaemon.INSTANCE.getStackTrace()); Thread.UncaughtExceptionHandler h = Thread.getDefaultUncaughtExceptionHandler(); if (h == null) { // If we have no handler, log and exit. System.logE(message, syntheticException); System.exit(2); } // Otherwise call the handler to do crash reporting. // We don't just throw because we're not the thread that // timed out; we're the thread that detected it. h.uncaughtException(Thread.currentThread(), syntheticException); }
public void run() { System.out.print("Spoustim vlakno s ID = " + idVlakna + "\n"); InetAddress adresa = socket.getInetAddress(); System.out.print( "Pripojil se klient z: " + adresa.getHostAddress() + "/" + adresa.getHostName() + "\n"); try { ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); String message = (String) ois.readObject(); System.out.println("Message Received: " + message); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); Thread.currentThread().sleep(5000); oos.writeObject("Hallo"); ois.close(); oos.close(); socket.close(); System.out.print("Ukoncuji vlakno s ID=" + idVlakna + "\n"); } catch (Exception e2) { e2.printStackTrace(); } }
/** * Initializes a new, existing Thread object with a runnable object, the given name and belonging * to the ThreadGroup passed as parameter. This is the method that the several public constructors * delegate their work to. * * @param group ThreadGroup to which the new Thread will belong * @param runnable a java.lang.Runnable whose method <code>run</code> will be executed by the new * Thread * @param threadName Name for the Thread being created * @param stackSize Platform dependent stack size * @throws IllegalThreadStateException if <code>group.destroy()</code> has already been done * @see java.lang.ThreadGroup * @see java.lang.Runnable */ private void create(ThreadGroup group, Runnable runnable, String threadName, long stackSize) { Thread currentThread = Thread.currentThread(); if (group == null) { group = currentThread.getThreadGroup(); } if (group.isDestroyed()) { throw new IllegalThreadStateException("Group already destroyed"); } this.group = group; synchronized (Thread.class) { id = ++Thread.count; } if (threadName == null) { this.name = "Thread-" + id; } else { this.name = threadName; } this.target = runnable; this.stackSize = stackSize; this.priority = currentThread.getPriority(); this.contextClassLoader = currentThread.contextClassLoader; // Transfer over InheritableThreadLocals. if (currentThread.inheritableValues != null) { inheritableValues = new ThreadLocal.Values(currentThread.inheritableValues); } // add ourselves to our ThreadGroup of choice this.group.addThread(this); }
public ClassLoader getClassLoader() { return classLoader == null ? classLoader = Thread.currentThread().getContextClassLoader() : classLoader; }
@Override public void handleMessage(Message msg) { Log.d(tag, "InsiderrService -- starting message"); // store the thread id, if for some reason it is different than the stored one, // we kill ourselves (because someone else started instead of us) SharedPreferences settings = getSharedPreferences(InsiderrService.PREFS_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); editor.putLong("THREADID", Thread.currentThread().getId()); editor.commit(); // Normally we would do some work here, like download a file. // For our sample, we just sleep for 15 seconds. while (InsiderrService.mRunning) { synchronized (this) { try { double sleeptime = InsiderrService.SleepTimes[ Math.min( InsiderrService.indexSleepTimes, InsiderrService.SleepTimes.length - 1)]; InsiderrService.indexSleepTimes += 1; Log.d(tag, String.format("Sleeping for: %.2f min", sleeptime)); Thread.sleep((int) (60 * 1000 * sleeptime)); Log.d(tag, "InsiderrService -- wakeup"); // check if someone else is in charge long threadid = settings.getLong("THREADID", 0); if (threadid != Thread.currentThread().getId()) { Log.d(tag, "InsiderrService -- someone else is in charge -- quitting"); break; } int numUpdates = getUpdates(); Log.d(tag, String.format("checking updates: %d new updates", numUpdates)); // stop service once we have a few updates. // we will be started again once the app is active if (numUpdates != 0) { Log.d(tag, "Stopping service - we got updates"); if (mService != null) { String[] system_note = { "Trending: this post", "This post might be interesting to you", "This post: so hot right now", "This post is on fire", "This post is winning Insiderr today" }; String[] post_note = { "Other Insiderrs are commenting...", "New comment...", "This comment might be interesting to you" }; String note = post_note[(new Random()).nextInt(post_note.length)]; if (numUpdates < 0) { note = system_note[(new Random()).nextInt(system_note.length)]; } mService.addNotification(this.mUpdatedKeys, note); this.mUpdatedKeys = null; Log.d(tag, "Stopping service - notified"); InsiderrService.indexSleepTimes = 0; } InsiderrService.mRunning = false; } } catch (Exception e) { } } } // Stop the service using the startId, so that we don't stop // the service in the middle of handling another job stopSelf(msg.arg1); }
public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { String imageFn = ((StringValue) arguments[0].next()).getStringValue(); imageLoaded = false; imageFailed = false; image = null; width = -1; depth = -1; System.setProperty("java.awt.headless", "true"); try { URL url = new URL(imageFn); image = Toolkit.getDefaultToolkit().getImage(url); } catch (MalformedURLException mue) { image = Toolkit.getDefaultToolkit().getImage(imageFn); } width = image.getWidth(this); depth = image.getHeight(this); while (!imageFailed && (width == -1 || depth == -1)) { try { java.lang.Thread.currentThread().sleep(50); } catch (Exception e) { // nop; } width = image.getWidth(this); depth = image.getHeight(this); } image.flush(); if ((width == -1 || depth == -1) && imageFailed) { // Maybe it's an EPS or PDF? // FIXME: this code is crude BufferedReader ir = null; String line = null; int lineLimit = 100; try { ir = new BufferedReader(new FileReader(new File(imageFn))); line = ir.readLine(); if (line != null && line.startsWith("%PDF-")) { // We've got a PDF! while (lineLimit > 0 && line != null) { lineLimit--; if (line.startsWith("/CropBox [")) { line = line.substring(10); if (line.indexOf("]") >= 0) { line = line.substring(0, line.indexOf("]")); } parseBox(line); lineLimit = 0; } line = ir.readLine(); } } else if (line != null && line.startsWith("%!") && line.indexOf(" EPSF-") > 0) { // We've got an EPS! while (lineLimit > 0 && line != null) { lineLimit--; if (line.startsWith("%%BoundingBox: ")) { line = line.substring(15); parseBox(line); lineLimit = 0; } line = ir.readLine(); } } else if (line != null && (line.startsWith("<?xml") || line.startsWith("<!DOCTYPE") || line.startsWith("<svg"))) { // We've got an SVG! while (lineLimit > 0 && line != null) { lineLimit--; if (line.contains("width=") && width == -1) { int pos = line.indexOf("width="); String ex = line.substring(pos + 7); int sqpos = ex.indexOf("'"); int dqpos = ex.indexOf("\""); pos = sqpos < dqpos && sqpos >= 0 ? sqpos : dqpos; width = convertUnits(ex.substring(0, pos)); } if (line.contains("height=") && depth == -1) { int pos = line.indexOf("height="); String ex = line.substring(pos + 8); int sqpos = ex.indexOf("'"); int dqpos = ex.indexOf("\""); pos = sqpos < dqpos && sqpos >= 0 ? sqpos : dqpos; depth = convertUnits(ex.substring(0, pos)); } if (width >= 0 && depth >= 0) { lineLimit = 0; } line = ir.readLine(); } } else { System.err.println("Failed to interpret image: " + imageFn); } } catch (Exception e) { System.err.println("Failed to load image: " + imageFn); width = -1; depth = -1; } if (ir != null) { try { ir.close(); } catch (Exception e) { // nop; } } } if (width >= 0) { Int64Value[] props = {new Int64Value(width), new Int64Value(depth)}; return new ArrayIterator(props); } else { return EmptyIterator.getInstance(); } }
public static void assertIsUIThread() { assert Looper.getMainLooper().getThread() == Thread.currentThread(); }
/** * Copies an array with all Threads which are in the same ThreadGroup as the receiver - and * subgroups - into the array <code>threads</code> passed as parameter. If the array passed as * parameter is too small no exception is thrown - the extra elements are simply not copied. * * @param threads array into which the Threads will be copied * @return How many Threads were copied over */ public static int enumerate(Thread[] threads) { Thread thread = Thread.currentThread(); return thread.getThreadGroup().enumerate(threads); }
/** Constructor for ImageIntrinsics */ public ImageIntrinsics(ExpressionContext context, String imageFn) { System.setProperty("java.awt.headless", "true"); image = Toolkit.getDefaultToolkit().getImage(imageFn); width = image.getWidth(this); while (!imageFailed && (width == -1 || depth == -1)) { try { java.lang.Thread.currentThread().sleep(50); } catch (Exception e) { // nop; } width = image.getWidth(this); depth = image.getHeight(this); } if (imageFailed) { // Maybe it's an EPS or PDF? // FIXME: this code is crude BufferedReader ir = null; String line = null; int lineLimit = 100; try { ir = new BufferedReader(new FileReader(new File(imageFn))); line = ir.readLine(); if (line != null && line.startsWith("%PDF-")) { // We've got a PDF! while (lineLimit > 0 && line != null) { lineLimit--; if (line.startsWith("/CropBox [")) { line = line.substring(10); if (line.indexOf("]") >= 0) { line = line.substring(0, line.indexOf("]")); } parseBox(line); lineLimit = 0; } line = ir.readLine(); } } else if (line != null && line.startsWith("%!") && line.indexOf(" EPSF-") > 0) { // We've got an EPS! while (lineLimit > 0 && line != null) { lineLimit--; if (line.startsWith("%%BoundingBox: ")) { line = line.substring(15); parseBox(line); lineLimit = 0; } line = ir.readLine(); } } } catch (Exception e) { // nop; } if (ir != null) { try { ir.close(); } catch (Exception e) { // nop; } } } }
/** Initialize the system class. Called after thread initialization. */ private static void initializeSystemClass() { // VM might invoke JNU_NewStringPlatform() to set those encoding // sensitive properties (user.home, user.name, boot.class.path, etc.) // during "props" initialization, in which it may need access, via // System.getProperty(), to the related system encoding property that // have been initialized (put into "props") at early stage of the // initialization. So make sure the "props" is available at the // very beginning of the initialization and all system properties to // be put into it directly. props = new Properties(); initProperties(props); // initialized by the VM // There are certain system configurations that may be controlled by // VM options such as the maximum amount of direct memory and // Integer cache size used to support the object identity semantics // of autoboxing. Typically, the library will obtain these values // from the properties set by the VM. If the properties are for // internal implementation use only, these properties should be // removed from the system properties. // // See java.lang.Integer.IntegerCache and the // sun.misc.VM.saveAndRemoveProperties method for example. // // Save a private copy of the system properties object that // can only be accessed by the internal implementation. Remove // certain system properties that are not intended for public access. sun.misc.VM.saveAndRemoveProperties(props); lineSeparator = props.getProperty("line.separator"); sun.misc.Version.init(); FileInputStream fdIn = new FileInputStream(FileDescriptor.in); FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out); FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err); setIn0(new BufferedInputStream(fdIn)); setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true)); setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true)); // Load the zip library now in order to keep java.util.zip.ZipFile // from trying to use itself to load this library later. loadLibrary("zip"); // Setup Java signal handlers for HUP, TERM, and INT (where available). Terminator.setup(); // Initialize any miscellenous operating system settings that need to be // set for the class libraries. Currently this is no-op everywhere except // for Windows where the process-wide error mode is set before the java.io // classes are used. sun.misc.VM.initializeOSEnvironment(); // The main thread is not added to its thread group in the same // way as other threads; we must do it ourselves here. Thread current = Thread.currentThread(); current.getThreadGroup().add(current); // register shared secrets setJavaLangAccess(); // Subsystems that are invoked during initialization can invoke // sun.misc.VM.isBooted() in order to avoid doing things that should // wait until the application class loader has been set up. // IMPORTANT: Ensure that this remains the last initialization action! sun.misc.VM.booted(); }
/** Constructor for ImageIntrinsics */ public ImageIntrinsics(String imageFn) { System.setProperty("java.awt.headless", "true"); // Hack. I expect the right way to do this is to always use a URL. // However, that means getting the base URI correct and dealing // with the various permutations of the file: URI scheme on different // platforms. So instead, what we're going to do is cheat. If it // starts with http: or ftp:, call it a URI. Otherwise, call it // a file. Also call it a file if the URI is malformed. URL imageUrl = null; if (imageFn.startsWith("http:") || imageFn.startsWith("ftp:") || imageFn.startsWith("file:")) { try { imageUrl = new URL(imageFn); } catch (MalformedURLException mue) { imageUrl = null; } } if (imageUrl != null) { image = Toolkit.getDefaultToolkit().getImage(imageUrl); } else { image = Toolkit.getDefaultToolkit().getImage(imageFn); } width = image.getWidth(this); while (!imageFailed && (width == -1 || depth == -1)) { try { java.lang.Thread.currentThread().sleep(50); } catch (Exception e) { // nop; } width = image.getWidth(this); depth = image.getHeight(this); } if (imageFailed) { // Maybe it's an EPS or PDF? // FIXME: this code is crude (and doesn't handle the URL case!!!) BufferedReader ir = null; String line = null; int lineLimit = 100; try { ir = new BufferedReader(new FileReader(new File(imageFn))); line = ir.readLine(); if (line != null && line.startsWith("%PDF-")) { // We've got a PDF! while (lineLimit > 0 && line != null) { lineLimit--; if (line.startsWith("/CropBox [")) { line = line.substring(10); if (line.indexOf("]") >= 0) { line = line.substring(0, line.indexOf("]")); } parseBox(line); lineLimit = 0; } line = ir.readLine(); } } else if (line != null && line.startsWith("%!") && line.indexOf(" EPSF-") > 0) { // We've got an EPS! while (lineLimit > 0 && line != null) { lineLimit--; if (line.startsWith("%%BoundingBox: ")) { line = line.substring(15); parseBox(line); lineLimit = 0; } line = ir.readLine(); } } else { System.err.println("Failed to interpret image: " + imageFn); } } catch (Exception e) { System.err.println("Failed to load image: " + imageFn); } if (ir != null) { try { ir.close(); } catch (Exception e) { // nop; } } } }