public void unregisterKeyStroke(KeyStroke ks, JComponent c) { // component may have already been removed from the hierarchy, we // need to look up the container using the componentKeyStrokeMap. ComponentKeyStrokePair ckp = new ComponentKeyStrokePair(c, ks); Container topContainer = componentKeyStrokeMap.get(ckp); if (topContainer == null) { // never heard of this pairing, so bail return; } Hashtable keyMap = containerMap.get(topContainer); if (keyMap == null) { // this should never happen, but I'm being safe Thread.dumpStack(); return; } Object tmp = keyMap.get(ks); if (tmp == null) { // this should never happen, but I'm being safe Thread.dumpStack(); return; } if (tmp instanceof JComponent && tmp == c) { keyMap.remove(ks); // remove the KeyStroke from the Map // System.out.println("removed a stroke" + ks); } else if (tmp instanceof Vector) { // this means there is more than one component reg for this key Vector v = (Vector) tmp; v.removeElement(c); if (v.isEmpty()) { keyMap.remove(ks); // remove the KeyStroke from the Map // System.out.println("removed a ks vector"); } } if (keyMap.isEmpty()) { // if no more bindings in this table containerMap.remove(topContainer); // remove table to enable GC // System.out.println("removed a container"); } componentKeyStrokeMap.remove(ckp); // Check for EmbeddedFrame case, they know how to process accelerators even // when focus is not in Java if (topContainer instanceof EmbeddedFrame) { ((EmbeddedFrame) topContainer).unregisterAccelerator(ks); } }
final void disableTrueDoubleBuffering() { if (useTrueDoubleBuffering) { if (!IGNORE_DISABLE_TRUE_DOUBLE_BUFFERING) { if (LOG_DISABLE_TRUE_DOUBLE_BUFFERING) { System.out.println("Disabling true double buffering for " + this); Thread.dumpStack(); } useTrueDoubleBuffering = false; RepaintManager.currentManager(this).doubleBufferingChanged(this); } } }
// public static final String showElementTreeAction = "showElementTree"; // ------------------------------------------------------------- public void openFile(String currDirStr, String currFileStr) { if (fileDialog == null) { fileDialog = new FileDialog(this); } fileDialog.setMode(FileDialog.LOAD); if (!(currDirStr.equals(""))) { fileDialog.setDirectory(currDirStr); } if (!(currFileStr.equals(""))) { fileDialog.setFile(currFileStr); } fileDialog.show(); String file = fileDialog.getFile(); // cancel pushed if (file == null) { return; } String directory = fileDialog.getDirectory(); File f = new File(directory, file); if (f.exists()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) // oldDoc.removeUndoableEditListener(undoHandler); /* if (elementTreePanel != null) { elementTreePanel.setEditor(null); } */ getEditor().setDocument(new PlainDocument()); fileDialog.setTitle(file); Thread loader = new FileLoader(f, editor1.getDocument()); loader.start(); } }
@Override public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); int ret = chooser.showOpenDialog(frame); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = chooser.getSelectedFile(); if (f.isFile() && f.canRead()) { Document oldDoc = getEditor().getDocument(); if (oldDoc != null) { oldDoc.removeUndoableEditListener(undoHandler); } if (elementTreePanel != null) { elementTreePanel.setEditor(null); } getEditor().setDocument(new PlainDocument()); frame.setTitle(f.getName()); Thread loader = new FileLoader(f, editor.getDocument()); loader.start(); } else { JOptionPane.showMessageDialog( getFrame(), "Could not open file: " + f, "Error opening file", JOptionPane.ERROR_MESSAGE); } }
protected void openFromPath(final String path) { Thread t = new Thread( new Runnable() { public void run() { final ArrayList<Airspace> airspaces = new ArrayList<Airspace>(); try { loadAirspacesFromPath(path, airspaces); } finally { SwingUtilities.invokeLater( new Runnable() { public void run() { setAirspaces(airspaces); setEnabled(true); getApp().setCursor(null); getApp().getWwd().redraw(); } }); } } }); this.setEnabled(false); getApp().setCursor(new Cursor(Cursor.WAIT_CURSOR)); t.start(); }
/** Second part of debugger start procedure. */ private void startDebugger() { threadManager = new ThreadManager(this); setBreakpoints(); updateWatches(); println(bundle.getString("CTL_Debugger_running"), STL_OUT); setDebuggerState(DEBUGGER_RUNNING); virtualMachine.resume(); // start refresh thread ................................................. if (debuggerThread != null) debuggerThread.stop(); debuggerThread = new Thread( new Runnable() { public void run() { for (; ; ) { try { Thread.sleep(5000); } catch (InterruptedException ex) { } if (getState() == DEBUGGER_RUNNING) threadGroup.refresh(); } } }, "Debugger refresh thread"); // NOI18N debuggerThread.setPriority(Thread.MIN_PRIORITY); debuggerThread.start(); }
/** Disconnects from running debugged process. */ public void disconnect() throws DebuggerException { threadGroup.setRemoteThreadGroup(null); if (remoteDebugger != null) { remoteDebugger.close(); remoteDebugger = null; } if (debuggerThread != null) { debuggerThread.interrupt(); debuggerThread.stop(); } super.finishDebugger(); synchronizer = null; }
public void actionPerformed(ActionEvent e) { Frame frame = getFrame(); JFileChooser chooser = new JFileChooser(); int ret = chooser.showSaveDialog(frame); if (ret != JFileChooser.APPROVE_OPTION) { return; } File f = chooser.getSelectedFile(); frame.setTitle(f.getName()); Thread saver = new FileSaver(f, editor.getDocument()); saver.start(); }
/** Disconnects from running debugged process. */ public void disconnect() throws DebuggerException { if (breakpointMain != null) { for (int x = 0; x < breakpointMain.length; x++) breakpointMain[x].remove(); breakpointMain = null; } try { if (virtualMachine != null) virtualMachine.dispose(); } catch (VMDisconnectedException e) { } if (threadManager != null) threadManager.finish(); if (debuggerThread != null) { debuggerThread.interrupt(); debuggerThread.stop(); } super.finishDebugger(); }
/** * Closes given {@link #transportManagers} of this <tt>Conference</tt> and removes corresponding * channel bundle. */ void closeTransportManager(TransportManager transportManager) { synchronized (transportManagers) { for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator(); i.hasNext(); ) { if (i.next() == transportManager) { i.remove(); // Presumably, we have a single association for // transportManager. break; } } // Close manager try { transportManager.close(); } catch (Throwable t) { logger.warn( "Failed to close an IceUdpTransportManager of" + " conference " + getID() + "!", t); // The whole point of explicitly closing the // transportManagers of this Conference is to prevent memory // leaks. Hence, it does not make sense to possibly leave // TransportManagers open because a TransportManager has // failed to close. if (t instanceof InterruptedException) Thread.currentThread().interrupt(); else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } }
private void loadProvidersIfNecessary() { ClassLoader currentLoader = Thread.currentThread().getContextClassLoader(); if (!classLoaders.contains(currentLoader)) { classLoaders.add(currentLoader); loadProviders(currentLoader); } }
@Override @SuppressWarnings("SleepWhileHoldingLock") public void run() { try { // initialize the statusbar status.removeAll(); JProgressBar progress = new JProgressBar(); progress.setMinimum(0); progress.setMaximum(doc.getLength()); status.add(progress); status.revalidate(); // start writing Writer out = new FileWriter(f); Segment text = new Segment(); text.setPartialReturn(true); int charsLeft = doc.getLength(); int offset = 0; while (charsLeft > 0) { doc.getText(offset, Math.min(4096, charsLeft), text); out.write(text.array, text.offset, text.count); charsLeft -= text.count; offset += text.count; progress.setValue(offset); try { Thread.sleep(10); } catch (InterruptedException e) { Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e); } } out.flush(); out.close(); } catch (IOException e) { final String msg = e.getMessage(); SwingUtilities.invokeLater( new Runnable() { public void run() { JOptionPane.showMessageDialog( getFrame(), "Could not save file: " + msg, "Error saving file", JOptionPane.ERROR_MESSAGE); } }); } catch (BadLocationException e) { System.err.println(e.getMessage()); } // we are done... get rid of progressbar status.removeAll(); status.revalidate(); }
public void run() { if (Thread.currentThread().isInterrupted()) return; // the task was cancelled because it's a duplicate or for some other reason URL fileUrl = this.wwTexture.fileStore.requestFile(this.wwTexture.getImageSource().toString()); if (fileUrl != null) { if (this.wwTexture.loadTextureData(fileUrl)) { this.wwTexture.notifyTextureLoaded(); } } }
@Override public Void doInBackground() { int current = 0; int lengthOfTask = 100; while (current <= lengthOfTask && !isCancelled()) { try { // dummy task Thread.sleep(50); } catch (InterruptedException ie) { return null; } setProgress(100 * current / lengthOfTask); current++; } return null; }
public void testDeadlock49178() throws Exception { // open the document final StyledDocument docu = support.openDocument(); // start closing it Thread closing = new Thread( new Runnable() { public void run() { support.close(false); // will block in notifyUnmodified() closingDone = true; } }); closing.start(); Thread processing = new Thread( new Runnable() { boolean second = false; public void run() { if (!second) { second = true; docu.render(this); // NbDocument.runAtomic(docu, this); } else { // inside readLock support.createPositionRef(0, Position.Bias.Forward); processingDone = true; } } }); synchronized (waitLock) { while (!inWait) waitLock.wait(); } processing.start(); Thread.sleep(1000); synchronized (waitLock) { shouldWait = false; waitLock.notifyAll(); } closing.join(10000); processing.join(10000); assertNull("No exception thrown", exception); assertTrue("Closing thread finished", closingDone); assertTrue("Processing thread finished", processingDone); }
/** * Constructs. * * @param display The VisAD display to use. * @throws DisplayException The VisAD display is <code>null</code>. * @throws VisADException VisAD failure. * @throws RemoteException Java RMI failure. */ public DisplayAdapter(DisplayImpl display) throws DisplayException, VisADException, RemoteException { if (display == null) { throw new DisplayException(getClass().getName() + ".<init>: " + "Display argument is null"); } this.display = display; updater = new Updater(); updater.setPriority(Thread.currentThread().getPriority() / 2); datumTable = new DatumTable(); scalarMapTable = new ScalarMapTable(); constantMapTable = new ConstantMapTable(); }
/** * Expires this <tt>Conference</tt>, its <tt>Content</tt>s and their respective <tt>Channel</tt>s. * Releases the resources acquired by this instance throughout its life time and prepares it to be * garbage collected. */ public void expire() { synchronized (this) { if (expired) return; else expired = true; } EventAdmin eventAdmin = videobridge.getEventAdmin(); if (eventAdmin != null) eventAdmin.sendEvent(EventFactory.conferenceExpired(this)); setRecording(false); if (recorderEventHandler != null) { recorderEventHandler.close(); recorderEventHandler = null; } Videobridge videobridge = getVideobridge(); try { videobridge.expireConference(this); } finally { // Expire the Contents of this Conference. for (Content content : getContents()) { try { content.expire(); } catch (Throwable t) { logger.warn( "Failed to expire content " + content.getName() + " of conference " + getID() + "!", t); if (t instanceof InterruptedException) Thread.currentThread().interrupt(); else if (t instanceof ThreadDeath) throw (ThreadDeath) t; } } // Close the transportManagers of this Conference. Normally, there // will be no TransportManager left to close at this point because // all Channels have expired and the last Channel to be removed from // a TransportManager closes the TransportManager. However, a // Channel may have expired before it has learned of its // TransportManager and then the TransportManager will not close. closeTransportManagers(); if (logger.isInfoEnabled()) { logger.info( "Expired conference " + getID() + ". " + videobridge.getConferenceCountString()); } } }
private synchronized void closeAll() { try { // Close all child window WindowManager.closeAll(); // Remove all child component pnlThread.setVisible(false); pnlUser.setVisible(false); pnlThread.removeAll(); clearAll(txtBoard); tblUser.setData(new Vector()); Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); MessageBox.showMessageDialog(this, e, Global.APP_NAME, MessageBox.ERROR_MESSAGE); } }
/** Cancel all active downloads. */ public void cancelActiveDownloads() { for (Component c : this.monitorPanel.getComponents()) { if (c instanceof DownloadMonitorPanel) { if (((DownloadMonitorPanel) c).thread.isAlive()) { DownloadMonitorPanel panel = (DownloadMonitorPanel) c; panel.cancelButtonActionPerformed(null); try { // Wait for thread to die before moving on long t0 = System.currentTimeMillis(); while (panel.thread.isAlive() && System.currentTimeMillis() - t0 < 500) { Thread.sleep(10); } } catch (Exception ignore) { } } } } }
/** * register keystrokes here which are for the WHEN_IN_FOCUSED_WINDOW case. Other types of * keystrokes will be handled by walking the hierarchy That simplifies some potentially hairy * stuff. */ public void registerKeyStroke(KeyStroke k, JComponent c) { Container topContainer = getTopAncestor(c); if (topContainer == null) { return; } Hashtable keyMap = containerMap.get(topContainer); if (keyMap == null) { // lazy evaluate one keyMap = registerNewTopContainer(topContainer); } Object tmp = keyMap.get(k); if (tmp == null) { keyMap.put(k, c); } else if (tmp instanceof Vector) { // if there's a Vector there then add to it. Vector v = (Vector) tmp; if (!v.contains(c)) { // only add if this keystroke isn't registered for this component v.addElement(c); } } else if (tmp instanceof JComponent) { // if a JComponent is there then remove it and replace it with a vector // Then add the old compoennt and the new compoent to the vector // then insert the vector in the table if (tmp != c) { // this means this is already registered for this component, no need to dup Vector<JComponent> v = new Vector<JComponent>(); v.addElement((JComponent) tmp); v.addElement(c); keyMap.put(k, v); } } else { System.out.println("Unexpected condition in registerKeyStroke"); Thread.dumpStack(); } componentKeyStrokeMap.put(new ComponentKeyStrokePair(c, k), topContainer); // Check for EmbeddedFrame case, they know how to process accelerators even // when focus is not in Java if (topContainer instanceof EmbeddedFrame) { ((EmbeddedFrame) topContainer).registerAccelerator(k); } }
/** Delay the starting until the time specified later(second). */ public void start() { // if (port != null) System.out.println(this + " starts: " + data); // runtime.startRegister(this); if (aruntime.isSuspend()) return; if (isAlive()) { // __wakeUp(); synchronized (this) { lastsleepon = this; lastwakeupthread = Thread.currentThread(); try { this.notify(); } catch (Exception e_) { drcl.Debug.error(this, "start()| " + e_, false); } } } else { // the thread is newly created setState(State_INACTIVE); super.start(); } }
/** * Starts the debugger. The method stops the current debugging (if any) and takes information from * the provided info (containing the class to start and arguments to pass it and name of class to * stop debugging in) and starts new debugging session. * * @param info debugger info about class to start * @exception DebuggerException if an error occures during the start of the debugger */ public void startDebugger(DebuggerInfo info) throws DebuggerException { debuggerInfo = info; if (remoteDebugger != null) finishDebugger(); // S ystem.out.println("startDebugger " + info); // NOI18N // RemoteDebugging support hostName = null; password = null; boolean local = true; if (info instanceof ReconnectDebuggerInfo) { ReconnectDebuggerInfo rdi = (ReconnectDebuggerInfo) info; hostName = rdi.getHostName(); password = rdi.getPassword(); local = false; } else if (info instanceof RemoteDebuggerInfo) { hostName = ((RemoteDebuggerInfo) info).getHostName(); password = ((RemoteDebuggerInfo) info).getPassword(); local = false; } boolean stopOnMain = info.getStopClassName() != null; stopOnMainFlag = stopOnMain; // S ystem.out.println ("ToolsDebugger.startDebugger " + info.getStopClassName ()); // NOI18N // T hread.dumpStack (); synchronizer = new RequestSynchronizer(); // open output window ... super.startDebugger(info); // start & init remote debugger ................................................ // process = null; if (local) { // create process & read password for local debugging // create starting string & NbProcessDescriptor NbProcessDescriptor debugerProcess; if (info instanceof ProcessDebuggerInfo) debugerProcess = ((ProcessDebuggerInfo) info).getDebuggerProcess(); else debugerProcess = ProcessDebuggerType.DEFAULT_DEBUGGER_PROCESS; HashMap map; if (info instanceof ToolsDebugger10Info) { map = Utils.processDebuggerInfo( info, "-debug", // NOI18N "sun.tools.debug.EmptyApp" // NOI18N ); map.put(ToolsDebugger10Type.JAVA_HOME_SWITCH, ((ToolsDebugger10Info) info).getJavaHome()); } else { if (info instanceof ToolsDebugger11Info) { String javaHome11 = ((ToolsDebugger11Info) info).getJavaHome(); if ((javaHome11 == null) || (javaHome11.trim().length() == 0)) { finishDebugger(); throw new DebuggerException(bundle.getString("EXC_JDK11_home_is_not_set")); } map = Utils.processDebuggerInfo( info, "-debug -nojit", // NOI18N "sun.tools.debug.EmptyApp" // NOI18N ); map.put(ToolsDebugger11Type.JAVA_HOME_SWITCH, javaHome11); } else { map = Utils.processDebuggerInfo( info, "-Xdebug", // NOI18N "sun.tools.agent.EmptyApp" // NOI18N ); } } MapFormat format = new MapFormat(map); String s = format.format( debugerProcess.getProcessName() + " " + debugerProcess.getArguments() // NOI18N ); println(s, ERR_OUT); // start process & read password ...................................... try { process = debugerProcess.exec(format); BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(process.getInputStream())); password = bufferedreader.readLine(); showOutput(process, ERR_OUT, ERR_OUT); connectInput(process); } catch (java.lang.Exception e) { finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_While_create_debuggee")) .format( new Object[] {format.format(debugerProcess.getProcessName()), e.toString()}), e); } if (password == null) { // no reply finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_While_connect_to_debuggee")) .format(new Object[] {format.format(debugerProcess.getProcessName())})); } if (password.indexOf("=") < 0) { // NOI18N // unexpected reply println(bundle.getString("CTL_Unexpected_reply") + ": " + password, ERR_OUT); showOutput(process, ERR_OUT + STD_OUT, ERR_OUT); finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_Unecpected_debugger_reply")) .format(new Object[] {password})); } password = password.substring(password.indexOf("=") + 1); // NOI18N println(bundle.getString("CTL_Password") + ": " + password, ERR_OUT); hostName = "127.0.0.1"; // NOI18N } // end of local debugging specific else if (info instanceof ReconnectDebuggerInfo) { println(bundle.getString("CTL_Reconnecting"), ERR_OUT | STD_OUT); } else println(bundle.getString("CTL_Connecting_to") + ": " + hostName + ":" + password, ERR_OUT); // start RemoteDebugger ................................................... try { remoteDebugger = new RemoteDebugger( hostName, password.length() < 1 ? null : password, new ToolsCallback(this), isShowMessages()); } catch (java.net.ConnectException e) { finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_Cannot_connect_to_debuggee")) .format(new Object[] {e.toString()}), e); } catch (Throwable e) { if (e instanceof ThreadDeath) throw (ThreadDeath) e; // e.printStackTrace (); finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_Cannot_connect_to_debuggee")) .format(new Object[] {e.toString()}), e); } // create arguments for main class ............................................... mainClassName = info.getClassName(); RemoteClass cls; String[] args = null; if ((mainClassName != null) && (mainClassName.length() > 0)) { String[] infoArgs = info.getArguments(); args = new String[infoArgs.length + 1]; args[0] = mainClassName; System.arraycopy(infoArgs, 0, args, 1, infoArgs.length); // args[0] = name of class // args[...] = parameters // find main class ......................................................... try { cls = remoteDebugger.findClass(mainClassName); } catch (Throwable e) { if (e instanceof ThreadDeath) throw (ThreadDeath) e; finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_Cannot_find_class")) .format(new Object[] {mainClassName, e.toString()}), e); } if (cls == null) { finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_Cannot_find_class")) .format(new Object[] {mainClassName, new ClassNotFoundException().toString()})); } } // set breakpoint on stop class method ............................................... if (stopOnMain) { RemoteClass stopClass = null; try { stopClass = remoteDebugger.findClass(stopClassName = info.getStopClassName()); } catch (Throwable e) { if (e instanceof ThreadDeath) throw (ThreadDeath) e; println( bundle.getString("MSG_Exc_while_finding_class") + stopClassName + '\n' + e, ERR_OUT); } if (stopClass == null) { println(bundle.getString("CTL_No_such_class") + ": " + stopClassName, ERR_OUT); } else { try { RemoteField[] rf = stopClass.getMethods(); int i, k = rf.length; Type t = Type.tMethod(Type.tVoid, new Type[] {Type.tArray(Type.tString)}); Type startT = Type.tMethod(Type.tVoid); RemoteField startM = null; RemoteField initM = null; RemoteField constM = null; for (i = 0; i < k; i++) { if (rf[i].getName().equals("main") && // NOI18N rf[i].getType().equals(t)) break; else if (rf[i].getName().equals("start") && // NOI18N rf[i].getType().equals(startT)) startM = rf[i]; else if (rf[i].getName().equals("init") && // NOI18N rf[i].getType().equals(startT)) initM = rf[i]; else if (rf[i].getName().equals("<init>") && // NOI18N rf[i].getType().equals(startT)) constM = rf[i]; } if (i < k) // [PENDING] stop on non main too !!!!!!!!!!!!!!!!!!!!! stopClass.setBreakpointMethod(rf[i]); // have main else if (initM != null) stopClass.setBreakpointMethod(initM); else if (startM != null) stopClass.setBreakpointMethod(startM); else if (constM != null) stopClass.setBreakpointMethod(constM); // S ystem.out.println ("Stop: " + (i <k) + " " + initM +" " + startM +" " + constM); // // NOI18N /* pendingBreakpoints = new RemoteField [1]; pendingBreakpoints [0] = rf[i]; pendingBreakpointsClass = stopClass;*/ } catch (Throwable e) { if (e instanceof ThreadDeath) throw (ThreadDeath) e; println(bundle.getString("MSG_Exc_while_setting_breakpoint") + '\n' + e, ERR_OUT); } } } // stopOnMain setBreakpoints(); updateWatches(); println(bundle.getString("CTL_Debugger_running"), STL_OUT); setDebuggerState(DEBUGGER_RUNNING); // run debugged class ............................................... if (args != null) { RemoteThreadGroup rtg = null; try { rtg = remoteDebugger.run(args.length, args); // threadGroup.setRemoteThreadGroup (rtg); } catch (Throwable e) { if (e instanceof ThreadDeath) throw (ThreadDeath) e; finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_While_calling_run")) .format(new Object[] {mainClassName, e.toString()}), e); } if (rtg == null) { finishDebugger(); throw new DebuggerException( new MessageFormat(bundle.getString("EXC_While_calling_run")) .format( new Object[] { mainClassName, "" // NOI18N })); } } // start refresh thread ................................................. if (debuggerThread != null) debuggerThread.stop(); debuggerThread = new Thread( new Runnable() { public void run() { for (; ; ) { try { Thread.sleep(5000); } catch (InterruptedException ex) { } if (getState() == DEBUGGER_RUNNING) try { threadGroup.threadChanged(); } catch (Throwable e) { if (e instanceof ThreadDeath) throw (ThreadDeath) e; if (e instanceof java.net.SocketException) { debuggerThread = null; try { finishDebugger(); } catch (Throwable ee) { if (ee instanceof ThreadDeath) throw (ThreadDeath) ee; } Thread.currentThread().stop(); } } } } }, "Debugger refresh thread"); // NOI18N debuggerThread.setPriority(Thread.MIN_PRIORITY); debuggerThread.start(); }
/** * This method is called when the focused component (and none of its ancestors) want the key * event. This will look up the keystroke to see if any chidren (or subchildren) of the specified * container want a crack at the event. If one of them wants it, then it will "DO-THE-RIGHT-THING" */ public boolean fireKeyboardAction(KeyEvent e, boolean pressed, Container topAncestor) { if (e.isConsumed()) { System.out.println("Acquired pre-used event!"); Thread.dumpStack(); } // There may be two keystrokes associated with a low-level key event; // in this case a keystroke made of an extended key code has a priority. KeyStroke ks; KeyStroke ksE = null; if (e.getID() == KeyEvent.KEY_TYPED) { ks = KeyStroke.getKeyStroke(e.getKeyChar()); } else { if (e.getKeyCode() != e.getExtendedKeyCode()) { ksE = KeyStroke.getKeyStroke(e.getExtendedKeyCode(), e.getModifiers(), !pressed); } ks = KeyStroke.getKeyStroke(e.getKeyCode(), e.getModifiers(), !pressed); } Hashtable keyMap = containerMap.get(topAncestor); if (keyMap != null) { // this container isn't registered, so bail Object tmp = null; // extended code has priority if (ksE != null) { tmp = keyMap.get(ksE); if (tmp != null) { ks = ksE; } } if (tmp == null) { tmp = keyMap.get(ks); } if (tmp == null) { // don't do anything } else if (tmp instanceof JComponent) { JComponent c = (JComponent) tmp; if (c.isShowing() && c.isEnabled()) { // only give it out if enabled and visible fireBinding(c, ks, e, pressed); } } else if (tmp instanceof Vector) { // more than one comp registered for this Vector v = (Vector) tmp; // There is no well defined order for WHEN_IN_FOCUSED_WINDOW // bindings, but we give precedence to those bindings just // added. This is done so that JMenus WHEN_IN_FOCUSED_WINDOW // bindings are accessed before those of the JRootPane (they // both have a WHEN_IN_FOCUSED_WINDOW binding for enter). for (int counter = v.size() - 1; counter >= 0; counter--) { JComponent c = (JComponent) v.elementAt(counter); // System.out.println("Trying collision: " + c + " vector = "+ v.size()); if (c.isShowing() && c.isEnabled()) { // don't want to give these out fireBinding(c, ks, e, pressed); if (e.isConsumed()) return true; } } } else { System.out.println("Unexpected condition in fireKeyboardAction " + tmp); // This means that tmp wasn't null, a JComponent, or a Vector. What is it? Thread.dumpStack(); } } if (e.isConsumed()) { return true; } // if no one else handled it, then give the menus a crack // The're handled differently. The key is to let any JMenuBars // process the event if (keyMap != null) { Vector v = (Vector) keyMap.get(JMenuBar.class); if (v != null) { Enumeration iter = v.elements(); while (iter.hasMoreElements()) { JMenuBar mb = (JMenuBar) iter.nextElement(); if (mb.isShowing() && mb.isEnabled()) { // don't want to give these out boolean extended = (ksE != null) && !ksE.equals(ks); if (extended) { fireBinding(mb, ksE, e, pressed); } if (!extended || !e.isConsumed()) { fireBinding(mb, ks, e, pressed); } if (e.isConsumed()) { return true; } } } } } return e.isConsumed(); }
/* * Main task. Executed in background thread. */ @Override public String doInBackground() throws Exception { if (myTaskName.equals("Get DownloadFile Info")) { if (!isCancelled()) { getFileInfo(); } } if (myTaskName.equals("Download Remote")) { if (!isCancelled()) { long theFileSize = getFileSize(); if (theFileSize != -1) { sendDownloadMessage(); int thePollInterval = Integer.parseInt(myProperties.getProperty("POLLINTERVAL")); long theCurrentTime = System.currentTimeMillis(); while (getStatus(theFileSize) && !isCancelled()) { if ((System.currentTimeMillis() - theCurrentTime) < thePollInterval * 1000) { Thread.sleep(thePollInterval * 1000 - System.currentTimeMillis() + theCurrentTime); } theCurrentTime = System.currentTimeMillis(); } } } } if (myTaskName.equals("Download Local Base")) { if (!isCancelled()) { downloadFileFromBase(); } } if (myTaskName.equals("Clean Remote Temp")) { if (!isCancelled()) { CleanRemoteTempDir(); } } if (myTaskName.equals("Clean Remote Base")) { if (!isCancelled()) { CleanRemoteBaseDir(); } } if (myTaskName.equals("Split Remote")) { if (!isCancelled()) { splitFileFromBase(); } } if (myTaskName.equals("Email Remote")) { if (!isCancelled()) { emailFileFromBase(); } } if (myTaskName.equals("Join Local")) { if (!isCancelled()) { joinFileFromLocalBase(); } } /** if(!isCancelled()) { CleanRemoteTempDir(); }* */ /** if(!isCancelled()) { getFileList(); }* */ /** if(!isCancelled()) { verifyAndSync(); }* */ return "Done"; }
private String currentThread(Thread t_) { if (t_ == null) t_ = Thread.currentThread(); return t_.toString(); }
protected void saveToFile() { if (this.fileChooser == null) { this.fileChooser = new JFileChooser(); this.fileChooser.setCurrentDirectory(new File(Configuration.getUserHomeDirectory())); } this.fileChooser.setDialogTitle("Choose Directory to Place Airspaces"); this.fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); this.fileChooser.setMultiSelectionEnabled(false); int status = this.fileChooser.showSaveDialog(null); if (status != JFileChooser.APPROVE_OPTION) return; final File dir = this.fileChooser.getSelectedFile(); if (dir == null) return; if (!dir.exists()) { //noinspection ResultOfMethodCallIgnored dir.mkdirs(); } final Iterable<AirspaceEntry> entries = this.getModel().getEntries(); Thread t = new Thread( new Runnable() { public void run() { try { java.text.DecimalFormat f = new java.text.DecimalFormat("####"); f.setMinimumIntegerDigits(4); int counter = 0; for (AirspaceEntry entry : entries) { Airspace a = entry.getAirspace(); AirspaceAttributes currentAttribs = a.getAttributes(); a.setAttributes(entry.getAttributes()); String xmlString = a.getRestorableState(); if (xmlString != null) { try { PrintWriter of = new PrintWriter( new File( dir, a.getClass().getName() + "-" + entry.getName() + "-" + f.format(counter++) + ".xml")); of.write(xmlString); of.flush(); of.close(); } catch (Exception e) { e.printStackTrace(); } } a.setAttributes(currentAttribs); } } finally { SwingUtilities.invokeLater( new Runnable() { public void run() { setEnabled(true); getApp().setCursor(null); getApp().getWwd().redraw(); } }); } } }); this.setEnabled(false); getApp().setCursor(new Cursor(Cursor.WAIT_CURSOR)); t.start(); }
protected void openFromFile() { if (this.fileChooser == null) { this.fileChooser = new JFileChooser(); this.fileChooser.setCurrentDirectory(new File(Configuration.getUserHomeDirectory())); } this.fileChooser.setDialogTitle("Choose Airspace File Directory"); this.fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); this.fileChooser.setMultiSelectionEnabled(false); int status = this.fileChooser.showOpenDialog(null); if (status != JFileChooser.APPROVE_OPTION) return; final File dir = this.fileChooser.getSelectedFile(); if (dir == null) return; Thread t = new Thread( new Runnable() { public void run() { final ArrayList<Airspace> airspaces = new ArrayList<Airspace>(); try { File[] files = dir.listFiles( new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("gov.nasa.worldwind.render.airspaces") && name.endsWith(".xml"); } }); for (File file : files) { String[] name = file.getName().split("-"); try { Class c = Class.forName(name[0]); Airspace airspace = (Airspace) c.newInstance(); BufferedReader input = new BufferedReader(new FileReader(file)); String s = input.readLine(); airspace.restoreState(s); airspaces.add(airspace); if (name.length >= 2) { airspace.setValue(AVKey.DISPLAY_NAME, name[1]); } } catch (Exception e) { e.printStackTrace(); } } } finally { SwingUtilities.invokeLater( new Runnable() { public void run() { setAirspaces(airspaces); setEnabled(true); getApp().setCursor(null); getApp().getWwd().redraw(); } }); } } }); this.setEnabled(false); getApp().setCursor(new Cursor(Cursor.WAIT_CURSOR)); t.start(); }
/** Standard Thread.run(). */ public /*final*/ void run() { if (Thread.currentThread() != this) { throw new WorkerThreadException( "not run() by the owning thread. Current thread:" + Thread.currentThread() + "---owning thread:" + this); } try { if (aruntime.debug && aruntime.isDebugEnabledAt(ARuntime.Debug_THREAD)) aruntime.println(ARuntime.Debug_THREAD, this, "THREAD STARTS"); for (; ; ) { // Note: // getTask() and recycle() must happen atomically because // during the time after this thread cannot get more tasks // from runtime.getTask() and before it goes to recycle() to // return workforce, another thread may produce a new task in // the ready queue (without this thread knowing it) and that // thread goes to the waiting state. Due to this racing, // the simulation could be stalled as no thread is actively // running to execute the new task in the ready queue. synchronized (aruntime) { if (mainContext == null || mainContext == DUMMY_CONTEXT) { // grab a task from worker pool nextTask = GETTING_TASK; // XXX: temporary for debug nextTask = aruntime.getTask(mainContext == null); if (nextTask != null) { // so null wont override DUMMY_CONTEXT mainContext = nextTask; nextTask = null; } else { setState(State_RECYCLING); sleepOn = this; aruntime.recycle(this); // return workforce in recycle() } } } if (state == State_RECYCLING) { setState(State_INACTIVE); // BOOKMARK1: // At this point, other threads may assign a new task // to this thread and start this thread, so check if // mainContext is being assigned within // the following synchronized claus synchronized (this) { if (mainContext == DUMMY_CONTEXT) mainContext = null; if (mainContext == null) { __sleepOn(this, State_INACTIVE, State_INACTIVE); continue; } else sleepOn = null; } } if (runtime.resetting) { throw new WorkerThreadInterruptedException(); } else if (aruntime.isSuspend()) { // go into sleep if runtime is suspended synchronized (this) { __sleepOn(this, State_PREACTIVE, State_ACTIVE); } } if (mainContext.threadGroup != null) { if (mainContext instanceof TaskNotify) { // mainContext is TaskNotify: // the object to be notified on is in "data" synchronized (mainContext.data) { if (aruntime.debug && aruntime.isDebugEnabledAt(ARuntime.Debug_THREAD)) aruntime.println( ARuntime.Debug_THREAD, this, "EXECUTING notify:" + mainContext.data + "," + System.currentTimeMillis()); mainContext.data.notify(); aruntime.nthreadsWaiting--; } mainContext = null; // workforce transfered to the waked up thread continue; } else if (getThreadGroup() != mainContext.threadGroup) { aruntime.immediatelyStart(mainContext); mainContext = null; // workforce transfered to new thread continue; } } if (aruntime.debug && aruntime.isDebugEnabledAt(ARuntime.Debug_THREAD)) aruntime.println(ARuntime.Debug_THREAD, this, "EXECUTING:" + mainContext); setState(State_ACTIVE); // runtime.runCheck(this); String method_ = "process()"; currentContext = mainContext; returnPort = currentContext.returnPort; // from server port, new context try { mainContext.execute(this); } catch (NullPointerException e_) { if (runtime == null) return; e_.printStackTrace(); drcl.Debug.error(info()); } catch (Exception e_) { e_.printStackTrace(); drcl.Debug.error(info()); } catch (SendReceiveException e_) { e_.printStackTrace(); drcl.Debug.error(info()); } currentContext.port = null; currentContext.data = null; finishing(); mainContext = DUMMY_CONTEXT; // to maintain the ownership of workforce if (!RECYCLING) { aruntime.remove(this); break; } if (nextTask != null) { // error checking if (mainContext != null && mainContext != DUMMY_CONTEXT) drcl.Debug.systemFatalError("task assigned to occupied thread:" + this); mainContext = nextTask; nextTask = null; } } // for(;;) drcl.Debug.systemFatalError("Unexpected finish at " + this); } catch (WorkerThreadInterruptedException e_) { // if (!runtime.resetting) { // e_.printStackTrace(); // drcl.Debug.systemFatalError( // "AWorkerThread terminates abnormally, " + this // + "\nManager: " + runtime.diag()); // } // Will releaseAllLocks()/cancelAllWaits() clean up the lock // structure in components? // Not if the thread comes across multiple components... if (mainContext != null && mainContext.port != null) releaseAllLocks(mainContext.port.host); aruntime.remove(this); } catch (NullPointerException e_) { if (runtime != null) { e_.printStackTrace(); drcl.Debug.error(info()); } } runtime = null; // become an orphan aruntime = null; }