List of usage examples for java.util Observer Observer
Observer
From source file:MyModel.java
public static void main(String[] argv) throws Exception { MyModel model = new MyModel(); model.addObserver(new Observer() { public void update(Observable o, Object arg) { }//from w w w .ja v a 2 s . c om }); model.setChanged(); Object arg = "new information"; model.notifyObservers(arg); }
From source file:org.hypertopic.RESTDatabaseTest.java
/** * Tests update notification from server until enter is pressed *//*ww w . j av a 2s . c om*/ public static void main(String[] args) { RESTDatabase db = new RESTDatabase("http://127.0.0.1:5984/test/"); Observer observer = new Observer() { public void update(Observable o, Object arg) { System.out.println("Updated at " + new Date()); } }; db.startListening(); db.addObserver(observer); try { System.in.read(); } catch (Exception e) { } }
From source file:kellinwood.zipsigner.cmdline.Main.java
public static void main(String[] args) { try {//from ww w .j a v a 2 s . com Options options = new Options(); CommandLine cmdLine = null; Option helpOption = new Option("h", "help", false, "Display usage information"); Option modeOption = new Option("m", "keymode", false, "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none"); modeOption.setArgs(1); Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file"); keyOption.setArgs(1); Option pwOption = new Option("p", "keypass", false, "Private key password"); pwOption.setArgs(1); Option certOption = new Option("c", "cert", false, "X.509 public key certificate file"); certOption.setArgs(1); Option sbtOption = new Option("t", "template", false, "Signature block template file"); sbtOption.setArgs(1); Option keystoreOption = new Option("s", "keystore", false, "Keystore file"); keystoreOption.setArgs(1); Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore"); aliasOption.setArgs(1); options.addOption(helpOption); options.addOption(modeOption); options.addOption(keyOption); options.addOption(certOption); options.addOption(sbtOption); options.addOption(pwOption); options.addOption(keystoreOption); options.addOption(aliasOption); Parser parser = new BasicParser(); try { cmdLine = parser.parse(options, args); } catch (MissingOptionException x) { System.out.println("One or more required options are missing: " + x.getMessage()); usage(options); } catch (ParseException x) { System.out.println(x.getClass().getName() + ": " + x.getMessage()); usage(options); } if (cmdLine.hasOption(helpOption.getOpt())) usage(options); Properties log4jProperties = new Properties(); log4jProperties.load(new FileReader("log4j.properties")); PropertyConfigurator.configure(log4jProperties); LoggerManager.setLoggerFactory(new Log4jLoggerFactory()); List<String> argList = cmdLine.getArgList(); if (argList.size() != 2) usage(options); ZipSigner signer = new ZipSigner(); signer.addAutoKeyObserver(new Observer() { @Override public void update(Observable observable, Object o) { System.out.println("Signing with key: " + o); } }); Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProvider = (Provider) bcProviderClass.newInstance(); KeyStoreFileManager.setProvider(bcProvider); signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider"); PrivateKey privateKey = null; if (cmdLine.hasOption(keyOption.getOpt())) { if (!cmdLine.hasOption(certOption.getOpt())) { System.out.println("Certificate file is required when specifying a private key"); usage(options); } String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL(); privateKey = signer.readPrivateKey(privateKeyUrl, keypw); } X509Certificate cert = null; if (cmdLine.hasOption(certOption.getOpt())) { if (!cmdLine.hasOption(keyOption.getOpt())) { System.out.println("Private key file is required when specifying a certificate"); usage(options); } URL certUrl = new File(certOption.getValue()).toURI().toURL(); cert = signer.readPublicKey(certUrl); } byte[] sigBlockTemplate = null; if (cmdLine.hasOption(sbtOption.getOpt())) { URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL(); sigBlockTemplate = signer.readContentAsBytes(sbtUrl); } if (cmdLine.hasOption(keyOption.getOpt())) { signer.setKeys("custom", cert, privateKey, sigBlockTemplate); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption(modeOption.getOpt())) { signer.setKeymode(modeOption.getValue()); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption((keystoreOption.getOpt()))) { String alias = null; if (!cmdLine.hasOption(aliasOption.getOpt())) { KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null); for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { alias = e.nextElement(); System.out.println("Signing with key: " + alias); break; } } else alias = aliasOption.getValue(); String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(), "SHA1withRSA", argList.get(0), argList.get(1)); } else { signer.setKeymode("auto-testkey"); signer.signZip(argList.get(0), argList.get(1)); } } catch (Throwable t) { t.printStackTrace(); } }
From source file:org.sakaiproject.entitybroker.impl.event.EventReceiverCoordinator.java
public void init() { // register a single observer for the EB system (switched from local observer) eventTrackingService.addObserver(new Observer() { public void update(Observable o, Object arg) { if (arg instanceof Event) { Event event = (Event) arg; handleEvent(event);// www. ja va2 s . c o m } } }); }
From source file:com.anrisoftware.globalpom.exec.script.ScriptCommandExec.java
/** * @see ScriptCommandExecFactory#create(CommandExecFactory) *//*from w w w. j a v a 2s . c o m*/ @Inject ScriptCommandExec(@Assisted CommandExecFactory execFactory) { this.exec = execFactory.create(); this.scriptFileObserver = new Observer() { @Override public void update(Observable o, Object arg) { ProcessTask task = (ProcessTask) o; deleteScriptFile(task); } }; exec.setObserver(scriptFileObserver); }
From source file:org.jcryptool.commands.ui.eclipseconsole.CommandsUiStartup.java
public void earlyStartup() { final IOConsole ioConsole = new IOConsole(Messages.CommandsUiStartup_consolename, null); ioConsole.setConsoleWidth(0);// w ww . j a v a 2s .c om ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { ioConsole }); CommandsUIPlugin.getDefault().setIoConsole(ioConsole); final CommandEvaluator evaluator = new CommandEvaluator(); final IOConsolePromptShell monitor = new IOConsolePromptShell(ioConsole) { @Override protected void sendPrompt(final IOConsoleOutputStream o) throws IOException { Display.getDefault().syncExec(new Runnable() { public void run() { Color prevColor = o.getColor(); int prevStyle = o.getFontStyle(); o.setColor(Display.getDefault().getSystemColor(SWT.COLOR_RED)); try { o.write(PROMPT); } catch (IOException e) { LogUtil.logError(CommandsUIPlugin.PLUGIN_ID, e); } o.setColor(prevColor); o.setFontStyle(prevStyle); } }); } @Override protected void initializeConsole(IOConsoleOutputStream o) { super.initializeConsole(o); try { o.write(Messages.CommandsUiStartup_welcome + Messages.CommandsUiStartup_welcome_tip); } catch (IOException e) { LogUtil.logError(CommandsUIPlugin.PLUGIN_ID, e); } } }; Observer monitorObserver = new Observer() { public void update(Observable o, Object arg) { String line = monitor.getLine(); String result = Messages.CommandsUiStartup_eval_error; try { result = evaluator.evaluate(line).getResult(); } catch (ParseException e) { LogUtil.logError(CommandsUIPlugin.PLUGIN_ID, e); } IOConsoleOutputStream outStream = ioConsole.newOutputStream(); try { outStream.write(result + "\n\n"); //$NON-NLS-1$ } catch (IOException e) { LogUtil.logError(CommandsUIPlugin.PLUGIN_ID, e); } try { outStream.close(); } catch (IOException e) { LogUtil.logError(CommandsUIPlugin.PLUGIN_ID, e); } } }; monitor.addObserver(monitorObserver); monitor.startMonitoring(); }
From source file:org.cloudfoundry.caldecott.client.TunnelAcceptor.java
public void run() { while (keepGoing) { try {/*from ww w .j a va 2 s .co m*/ logger.trace("Waiting for client connection"); Socket sourceSocket = serverSocket.accept(); logger.debug("Accepted client connection"); TunnelHandler handler = new TunnelHandler(sourceSocket, tunnelFactory, taskExecutor); handler.addObserver(new Observer() { public void update(Observable observable, Object o) { if (logger.isDebugEnabled()) { logger.debug("Notified that " + observable + " is now " + o); } handlers.remove(observable); } }); handlers.put(handler, true); handler.start(); } catch (SocketTimeoutException ste) { } catch (IOException e) { if (!keepGoing && serverSocket.isClosed()) { // time to quit so we can ignore this exception } else { throw new TunnelException("Error while accepting connections", e); } } } if (!handlers.isEmpty()) { while (!handlers.isEmpty()) { logger.debug("Waiting for " + handlers.size() + " client connections to close"); for (TunnelHandler handler : handlers.keySet()) { logger.debug("Poking " + handler); handler.poke(); } try { Thread.sleep(10000); } catch (InterruptedException ignore) { } } } logger.info("Completed acceptor thread for: " + this); }
From source file:dmh.kuebiko.view.NoteStackFrame.java
/** * Create the frame.//ww w . ja v a 2s .c om */ public NoteStackFrame(NoteManager noteMngr) { this.noteMngr = noteMngr; // Setup the various actions for the frame. noteMngr.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { boolean stackChanged = (Boolean) arg; toggleUnsavedChangeIndicator(stackChanged); if (!stackChanged) { notePanel.getHuxleyUiManager().resetTextChanged(); } } }); ActionObserverUtil.registerEnMass(actionMngr, observable, new NewNoteAction(this), new OpenNoteAction(this), new DeleteNoteAction(this), new RenameNoteAction(this), new SaveStackAction(this)); // Build the menus. menuBar = new JMenuBar(); setJMenuBar(menuBar); fileMenu = new JMenu("File"); menuBar.add(fileMenu); newNoteMenuItem = new JMenuItem(actionMngr.getAction(NewNoteAction.class)); fileMenu.add(newNoteMenuItem); JMenuItem openNoteMenuItem = new JMenuItem(actionMngr.getAction(OpenNoteAction.class)); fileMenu.add(openNoteMenuItem); deleteNoteMenuItem = new JMenuItem(actionMngr.getAction(DeleteNoteAction.class)); fileMenu.add(deleteNoteMenuItem); renameNoteMenuItem = new JMenuItem(actionMngr.getAction(RenameNoteAction.class)); fileMenu.add(renameNoteMenuItem); fileMenu.addSeparator(); newStackMenuItem = new JMenuItem(actionMngr.getAction(NewStackAction.class)); fileMenu.add(newStackMenuItem); openStackMenuItem = new JMenuItem(actionMngr.getAction(OpenStackAction.class)); fileMenu.add(openStackMenuItem); fileMenu.addSeparator(); closeMenuItem = new JMenuItem("Close"); closeMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); closeMenuItem.setEnabled(false); fileMenu.add(closeMenuItem); closeAllMenuItem = new JMenuItem("Close All"); closeAllMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.SHIFT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); closeAllMenuItem.setEnabled(false); fileMenu.add(closeAllMenuItem); fileMenu.addSeparator(); saveMenuItem = new JMenuItem(actionMngr.getAction(SaveStackAction.class)); fileMenu.add(saveMenuItem); saveAllMenuItem = new JMenuItem("Save All"); saveAllMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.SHIFT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); saveAllMenuItem.setEnabled(false); fileMenu.add(saveAllMenuItem); editMenu = new JMenu("Edit"); menuBar.add(editMenu); undoMenuItem = new JMenuItem("Undo"); undoMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_Z, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); editMenu.add(undoMenuItem); redoMenuItem = new JMenuItem("Redo"); // FIXME mac-specific keyboard shortcut redoMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.SHIFT_MASK | Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); editMenu.add(redoMenuItem); editMenu.addSeparator(); cutMenuItem = new JMenuItem(actionMngr.getAction(DefaultEditorKit.CutAction.class)); cutMenuItem.setText("Cut"); cutMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); editMenu.add(cutMenuItem); copyMenuItem = new JMenuItem(actionMngr.getAction(DefaultEditorKit.CopyAction.class)); copyMenuItem.setText("Copy"); copyMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); editMenu.add(copyMenuItem); pasteMenuItem = new JMenuItem(actionMngr.getAction(DefaultEditorKit.PasteAction.class)); pasteMenuItem.setText("Paste"); pasteMenuItem.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_V, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); editMenu.add(pasteMenuItem); textMenu = new JMenu("Text"); menuBar.add(textMenu); JMenu windowMenu = new JMenu("Window"); menuBar.add(windowMenu); initialize(); additionalSetup(); }
From source file:com.github.nethad.clustermeister.provisioning.jppf.LocalDriverBuilder.java
@Override protected ClustermeisterLauncher doBuild() { JPPFDriverConfigurationSource.serverPort = serverPort; JPPFDriverConfigurationSource.managementPort = managementPort; JPPFDriverConfigurationSource.jvmOptions = configuration .getString(ConfigurationKeys.JVM_OPTIONS_LOCAL_DRIVER, ""); Map<String, String> loadBalancingConfigValues = new DriverLoadBalancing(configuration) .getLoadBalancingConfigValues(); if (loadBalancingConfigValues.isEmpty()) { // logger.info("No load balancing settings set."); } else {//from w w w.j a v a 2 s .c o m for (Map.Entry<String, String> entry : loadBalancingConfigValues.entrySet()) { // logger.info("{} => {}", entry.getKey(), entry.getValue()); } } JPPFDriverConfigurationSource.loadBalancing = new DriverLoadBalancing(configuration) .getLoadBalancingConfigValues(); final ClustermeisterLauncher launcher = new ClustermeisterDriverLauncher(true); final AtomicBoolean initialized = new AtomicBoolean(false); final Monitor initializationMonitor = new Monitor(false); final Monitor.Guard isInitialized = new Monitor.Guard(initializationMonitor) { @Override public boolean isSatisfied() { return initialized.get(); } }; launcher.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { initializationMonitor.enter(); try { initialized.set(true); } finally { initializationMonitor.leave(); } } }); Thread driverThread = new Thread(new Runnable() { @Override public void run() { try { launcher.doLaunch(true, ClustermeisterProcessLauncher.StreamSink.LOG); } catch (Throwable ex) { logger.warn("Execption from local driver thread.", ex); } } }); driverThread.setName(String.format("%s-%s", DRIVER_THREAD_NAME, driverThread.getId())); driverThread.start(); //wait for driver to initialize. initializationMonitor.enter(); try { try { initializationMonitor.waitFor(isInitialized); } catch (InterruptedException ex) { logger.warn("Interrupted while waiting for local driver to initialize! " + "Initialization may not be complete.", ex); } } finally { initializationMonitor.leave(); } return launcher; }
From source file:ggikko.me.steppertest.stepper.SteppersAdapter.java
@Override public void onBindViewHolder(final SteppersViewHolder holder, final int position) { final SteppersItem steppersItem = items.get(position); holder.setChecked(position < currentStep); if (holder.isChecked()) { holder.roundedView.setChecked(true); } else {// w w w .ja va 2 s . c o m holder.roundedView.setChecked(false); holder.roundedView.setText(position + 1 + ""); } if (position == currentStep || holder.isChecked()) holder.roundedView.setCircleAccentColor(); else holder.roundedView.setCircleGrayColor(); holder.textViewLabel.setText(steppersItem.getLabel()); holder.textViewSubLabel.setText(steppersItem.getSubLabel()); holder.linearLayoutContent .setVisibility(position == currentStep || position == beforeStep ? View.VISIBLE : View.GONE); holder.buttonContinue.setEnabled(steppersItem.isPositiveButtonEnable()); steppersItem.addObserver(new Observer() { @Override public void update(Observable observable, Object data) { if (observable != null) { SteppersItem item = (SteppersItem) observable; holder.buttonContinue.setEnabled(item.isPositiveButtonEnable()); } } }); if (position == getItemCount() - 1) holder.buttonContinue.setText(context.getResources().getString(R.string.step_finish)); else holder.buttonContinue.setText(context.getResources().getString(R.string.step_continue)); holder.buttonContinue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (position == getItemCount() - 1) config.getOnFinishAction().onFinish(); else nextStep(); } }); if (config.getOnCancelAction() != null) holder.buttonCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { config.getOnCancelAction().onCancel(); previousStep(); } }); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //FrameLayout frameLayout = (FrameLayout) inflater.inflate(R.layout.frame_layout, holder.frameLayout, true); if (frameLayoutIds.get(position) == null) frameLayoutIds.put(position, findUnusedId(holder.itemView)); //frameLayout.setId(frameLayoutIds.get(position)); if (config.getFragmentManager() != null && steppersItem.getFragment() != null) { holder.frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.transparent)); holder.frameLayout.setTag(frameLayoutName()); if (fragmentTransaction == null) { fragmentTransaction = fragmentManager.beginTransaction(); } String name = makeFragmentName(steppersView.getId(), position); Fragment fragment = fragmentManager.findFragmentByTag(name); if (position < beforeStep) { if (fragment != null) { if (BuildConfig.DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + fragment); fragmentTransaction.detach(fragment); } } else if (position == beforeStep || position == currentStep) { if (fragment != null) { if (BuildConfig.DEBUG) Log.v(TAG, "Attaching item #" + position + ": f=" + fragment + " d=" + fragment.isDetached()); fragmentTransaction.attach(fragment); } else { fragment = steppersItem.getFragment(); if (BuildConfig.DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment + " n=" + name); fragmentTransaction.add(steppersView.getId(), fragment, name); } } if (fragmentTransaction != null) { fragmentTransaction.commitAllowingStateLoss(); fragmentTransaction = null; fragmentManager.executePendingTransactions(); } if (fragmentManager.findFragmentByTag(name) != null && fragmentManager.findFragmentByTag(name).getView() != null) { View fragmentView = fragmentManager.findFragmentByTag(name).getView(); if (fragmentView.getParent() != null && frameLayoutName() != ((View) fragmentView.getParent()).getTag()) { steppersView.removeViewInLayout(fragmentView); holder.frameLayout.removeAllViews(); holder.frameLayout.addView(fragmentView); } } } if (beforeStep == position) { holder.linearLayoutContent.setVisibility(View.GONE); // AnimationUtils.hide(holder.linearLayoutContent); } if (currentStep == position && !steppersItem.isDisplayed()) { steppersItem.setDisplayed(true); } }