/** * Notify all of our observers of an event * * @param event */ public void notifyObservers(int event) { synchronized (mObservers) { for (Observer o : mObservers) { o.update(this, event); } } }
public void notifyObservers() { Iterator iter = observers.iterator(); while (iter.hasNext()) { Observer observer = (Observer) iter.next(); observer.update(); } }
protected static void convertAbbreviations( BaseReader reader, BaseWriter writer, Observer observer, ProgressInfo progress) throws Exception { Set<String> keys = reader.getAbbreviationKeys(); if (keys == null) { log.info("No abbreviations available"); return; } log.info("Number of abbreviations: {}", keys.size()); // Update progress observer.update(progress.setMessage("Sorting Abbreviations"), null); ArrayList<String> sortedKeys = new ArrayList<String>(keys.size()); for (String key : keys) { sortedKeys.add(key); } // Create Collator and sort abbreviations Collator collator = createCollator(writer); if (collator != null) { Collections.sort(sortedKeys, collator); } else { log.warn("Collator couldn't be created, sorting of Abbreviations is skipped"); } // Update progress observer.update(progress.setMessage("Converting Abbreviations"), null); for (Iterator<String> iterator = sortedKeys.iterator(); iterator.hasNext(); ) { String abbr = iterator.next(); AbbreviationInfo abbrInfo = reader.getAbbreviationInfo(abbr); String definition = abbrInfo.getAbbreviation(); if (abbr == null || definition == null || abbr.trim().equals("") || definition.trim().equals("")) { log.info("Abbreviation {} is excluded", abbrInfo); continue; } abbrInfo.setAbbreviation(abbrInfo.getAbbreviation().trim()); abbrInfo.setDefinition(abbrInfo.getDefinition().trim()); writer.saveAbbreviationInfo(reader.getAbbreviationInfo(abbr)); } writer.flush(); }
/** * This method is the main function of the thread of the collective. It does housekeeping and * regularly talks to peers to exchange information. It can be stopped by calling <code>close() * </code>. * * @see #close() */ public final void run() { while (shouldLive) { // try{ System.gc(); removeOldStuff(); if (!refresh()) { Address[] a = observer.getPeerAddresses(); if (a != null) synchronized (cache) { for (int i = 0; i < a.length; ++i) cache.put(a[i].name, new ContributionBox(a[i], null)); } } for (int i = 0; i < REFRESHRATE; i += 1000) { try { Thread.sleep(1000); } catch (InterruptedException e) { shouldLive = false; } if (shouldLive == false) break; Thread.yield(); } /*} catch( RuntimeException e ) { Logger.error( "Collective#run()", "Runtime exception caught, something is going wrong",e); }*/ } cache = null; observer = null; }
public void setActive(Simulation simulation, Visualizer vis) { this.simulation = simulation; this.visualizer = vis; simulation.addObserver(simObserver); simObserver.update(null, null); }
private void callVanishObserver(Object ptn, Match m) { SikuliEventVanish se = new SikuliEventVanish(ptn, m, _region); Object ao = _vanishOb.get(ptn); Observer.addEvent(_names.get(ptn), se); if (ao != null && ao instanceof SikuliEventObserver) { ((SikuliEventObserver) _vanishOb.get(ptn)).targetVanished(se); } }
private void callAppearObserver(Object ptn, Match m) { SikuliEventAppear se = new SikuliEventAppear(ptn, m, _region); Object ao = _appearOb.get(ptn); Observer.addEvent(_names.get(ptn), se); if (ao != null && ao instanceof SikuliEventObserver) { ((SikuliEventObserver) _appearOb.get(ptn)).targetAppeared(se); } }
public V put(K key, V value) { V v = super.put(key, value); if (ob != null) { ob.update(null, null); } return v; }
@SuppressWarnings("null") @Override public void notifyObservers(final Object arg) { TravelMvcWrapperBean wrapper = null; if (arg instanceof TravelMvcWrapperBean) { wrapper = (TravelMvcWrapperBean) arg; } else if (arg instanceof Object[]) { final Object[] args = (Object[]) arg; if (args != null && args.length > 0 && args[0] instanceof TravelMvcWrapperBean) { wrapper = (TravelMvcWrapperBean) args[0]; } } final String eventName = wrapper.getMethodToCall(); for (final Observer observer : getObservers().get(eventName)) { observer.update(this, arg); } clearChanged(); }
protected static void convertMediaResources( BaseReader reader, BaseWriter writer, Observer observer, ProgressInfo progress) throws Exception { Set<String> keys = reader.getMediaResourceKeys(); if (keys == null) { log.info("No media resources available"); return; } log.info("Number of media resources: {}", keys.size()); // Update progress observer.update(progress.setMessage("Sorting Media Resources"), null); ArrayList<String> sortedKeys = new ArrayList<String>(keys.size()); for (String key : keys) { sortedKeys.add(key); } // Create Collator and sort articles Collator collator = createCollator(writer); if (collator != null) { Collections.sort(sortedKeys, collator); } else { log.warn("Collator couldn't be created, sorting of Media Resources is skipped"); } // Update progress observer.update(progress.setMessage("Converting Media Resources"), null); for (Iterator<String> iterator = sortedKeys.iterator(); iterator.hasNext(); ) { String sortedKey = iterator.next(); MediaResourceInfo mediaInfo = reader.getMediaResourceInfo(new MediaResourceKey(sortedKey)); mediaInfo.getKey().setResourceKey(mediaInfo.getKey().getResourceKey()); writer.saveMediaResourceInfo(mediaInfo); } writer.flush(); }
private void setupUpdateIsCalledThenFails(Observer mockObserver) { mockObserver.update(anyObject(Observable.class), anyObject()); expectLastCall() .andAnswer( new IAnswer<Object>() { @Override public Object answer() throws Throwable { fail(); return null; } }); }
/** * Handles a message. Knows type "collectiveUpdate-"+name only. It is the responsibility of the * owner to propagate messages of this type using this method. */ public boolean handleMessage(Message m, Object o) { if (!shouldLive || !m.getType().equals("collectiveUpdate-" + name)) return false; final String logSender = observer + "#collectiveUpdate"; Logger.debug(logSender, "Update from " + m.getSender()); /**/ if (!m.getRecipient().name.equals(contributor.getName())) Logger.warning( logSender, "Recipient and my contributor are not the same:\n" + "Recipient: " + m.getRecipient().name + "\n" + "Contributor: " + contributor.getName(), null); /**/ Collective c = (Collective) o; // --- reset array representations cacheCollection = null; commandCollection = null; // --- remove possible garbage cache.remove(m.getRecipient().name); c.cache.remove(m.getRecipient().name); cache.remove(m.getSender().name); c.cache.remove(m.getSender().name); // --- sending our contributions if (contributor == null) Logger.warning(logSender, "Non-contributor observer is known by " + m.getSender(), null); updateLocalInfo(); m.setReply(this); // --- update containers repairSenderAddress(c, m.getSender()); merge(c); observer.collectiveUpdated((ContributionBox) cache.get(m.getSender().name)); return true; }
private void callChangeObserver(FindResults results) throws AWTException { for (Integer n : _changeOb.keySet()) { List<Match> changes = new ArrayList<Match>(); for (int i = 0; i < results.size(); i++) { FindResult r = results.get(i); if (r.getW() * r.getH() >= n) { changes.add(_region.toGlobalCoord(new Match(r, _region.getScreen()))); } } if (changes.size() > 0) { _countc.put(n, _countc.get(n) + 1); SikuliEventChange se = new SikuliEventChange(changes, _region); Object ao = _changeOb.get(n); Observer.addEvent(_cnames.get(n), se); if (ao instanceof SikuliEventObserver) { ((SikuliEventObserver) _changeOb.get(n)).targetChanged(se); } } } }
/** * If {@code hasChanged()} returns {@code true}, calls the {@code update()} method for every * observer in the list of observers using null as the argument. Afterwards, calls {@code * clearChanged()}. * * <p>Equivalent to calling {@code notifyObservers(null)}. */ @Override public void notifyObservers() { for (Observer observer : observers) { observer.notify(); } }
public void notifyObservers(Observable observable, String availability) { System.out.println("Notifying to all the subscribers when product became available"); for (Observer ob : observers) { ob.update(observable, this.availability); } }
public <PSC> void removeAppearObserver(PSC ptn) { Observer.remove(_names.get(ptn)); _names.remove(ptn); _appearOb.remove(ptn); _state.remove(ptn); }
protected static void convertArticles( BaseReader reader, BaseWriter writer, Observer observer, ProgressInfo progress) throws Exception { log.info("Started converting articles: Size {}", reader.getWords().size()); // Update progress observer.update(progress.setMessage("Mapping and Sorting Articles"), null); // Clone words to speed up the process (it can be based on buffered list) List<String> srcWords = new ArrayList<String>(reader.getWords()); // Mappings and redirects Map<Integer, String> srcMappings = reader.getAdaptedWordsMappings(); Map<Integer, Integer> srcRedirects = reader.getWordsRedirects(); // Create Collator and sort articles Collator collator = createCollator(writer); // Create and initialize words mapper ConversionWordsMapper wordsMapper = new ConversionWordsMapper(collator, srcWords, srcMappings, srcRedirects); wordsMapper.init(); List<String> normWords = wordsMapper.getNormalizedWords(); // Update progress observer.update(progress.setMessage("Converting Articles"), null); for (int i = 0; i < normWords.size(); i++) { String curWord = normWords.get(i); int oldWordId = wordsMapper.getOldWordId(curWord); // Word info to retrieve articles. Can't be moved outside because // it' overridden every time article is retrieved. WordInfo oldWordInfo = new WordInfo(oldWordId); oldWordInfo.setId(oldWordId); ArticleInfo inArticleInfo = reader.getAdaptedArticleInfo(oldWordInfo); if (inArticleInfo == null || inArticleInfo.getArticle() == null) { log.warn("Couldn't find article for {}", oldWordInfo); throw new IllegalStateException("Couldn't find article for " + oldWordInfo); } WordInfo newWordInfo = new WordInfo(i, curWord); // Add mapping if any String newMapping = wordsMapper.getNewWordMappingByOldWordId(oldWordId); if (newMapping != null) { newWordInfo.setWordMapping(newMapping); } // Add redirect if any int newRedirectToId = wordsMapper.getNewWordRedirect(oldWordId); if (newRedirectToId >= 0 && newRedirectToId != i) { // Don't allow redirects to itself newWordInfo.setRedirectToId(newRedirectToId); } ArticleInfo outArticleInfo = new ArticleInfo(newWordInfo, inArticleInfo.getArticle()); writer.saveAdaptedArticleInfo(outArticleInfo); // if (i > 10000) break; } writer.flush(); }
public <PSC> void removeVanishObserver(PSC ptn) { Observer.remove(_names.get(ptn)); _names.remove(ptn); _vanishOb.remove(ptn); _state.remove(ptn); }
public void removeChangeObserver(int threshold) { Observer.remove(_cnames.get(threshold)); _names.remove(threshold); _changeOb.remove(new Integer(threshold)); _minChanges = getMinChanges(); }
@Override public void notifyObservers() { for (final Observer observer : m_listeners) { observer.update(null, null); } }
private TuningResDTO buildResOnValidPeriods( List<PeriodRatingDTO> periods, SortedMap<Date, Number> mapFromQuotationsClose, Quotations quotations, Stock stock, Date startDate, Date endDate, String analyseName, SortedMap<Date, double[]> calcOutput, String evtDefInfo, Observer observer) throws IOException, InvalidAlgorithmParameterException { String trendFile = "noOutputAvailable"; String chartFile = "noChartAvailable"; Double trendFollowProfit = 1.00; Boolean generateBuySellCsv = MainPMScmd.getMyPrefs().getBoolean("autoporfolio.generatecsv", true); Boolean generateSmaCmpOutChart = MainPMScmd.getMyPrefs().getBoolean("autoporfolio.generatepng", true); // Init output file String endDateStamp = ""; if (MainPMScmd.getMyPrefs().getBoolean("perceptron.stampoutput", false)) { endDateStamp = new SimpleDateFormat("yyyyMMdd").format(endDate); } BufferedWriter csvWriter = null; String fileName = "noOutputAvailable"; if (generateBuySellCsv) { fileName = "autoPortfolioLogs" + File.separator + analyseName + stock.getSymbol() + "_" + evtDefInfo + "_BuyAndSellRecords" + endDateStamp + ".csv"; File file = new File(System.getProperty("installdir") + File.separator + fileName); file.delete(); csvWriter = new BufferedWriter(new FileWriter(file)); csvWriter.write("Date, Quotations, Bearish, Bullish, Output \n"); } // Other init BigDecimal lastClose = (BigDecimal) mapFromQuotationsClose.get(mapFromQuotationsClose.lastKey()); Double csvDispFactor = 1.00; SortedMap<Date, Double> buySerie = new TreeMap<Date, Double>(); SortedMap<Date, Double> sellSerie = new TreeMap<Date, Double>(); int lastRealisedBullIdx = -1; PeriodRatingDTO previousPeriod = null; for (PeriodRatingDTO currentPeriod : periods) { // Exports if (generateBuySellCsv || generateSmaCmpOutChart) { // csv gaps SortedMap<Date, Number> gapQuotationMap; if (generateBuySellCsv && previousPeriod != null && (gapQuotationMap = mapFromQuotationsClose.subMap( previousPeriod.getTo(), currentPeriod.getFrom())) .size() > 1) { for (Date gapDate : gapQuotationMap.keySet()) { Double closeForGapDate = gapQuotationMap.get(gapDate).doubleValue(); double[] output = calcOutput.get(gapDate); exportLine( generateBuySellCsv, false, csvDispFactor, csvWriter, buySerie, sellSerie, gapDate, closeForGapDate, EventType.NONE, output); } } previousPeriod = currentPeriod; // export period SortedMap<Date, Number> periodQuotationMap = mapFromQuotationsClose.subMap(currentPeriod.getFrom(), currentPeriod.getTo()); EventType periodTrend = EventType.valueOf(currentPeriod.getTrend()); for (Date periodInnerDate : periodQuotationMap.keySet()) { Double closeForInnerDate = periodQuotationMap.get(periodInnerDate).doubleValue(); double[] output = calcOutput.get(periodInnerDate); exportLine( generateBuySellCsv, generateSmaCmpOutChart, csvDispFactor, csvWriter, buySerie, sellSerie, periodInnerDate, closeForInnerDate, periodTrend, output); } } // Calculate profit if (EventType.valueOf(currentPeriod.getTrend()).equals(EventType.BULLISH) && currentPeriod.isRealised()) { lastRealisedBullIdx = periods.indexOf(currentPeriod); Double followPriceRateOfChange = currentPeriod.getPriceRateOfChange(); if (followPriceRateOfChange.isNaN() || followPriceRateOfChange.isInfinite()) { String message = "Error calculating followPriceRateOfChange for " + stock.getFriendlyName() + " : " + currentPeriod; LOGGER.error(message); throw new InvalidAlgorithmParameterException(message); } // Follow Profit if (LOGGER.isDebugEnabled()) LOGGER.debug( "Buy : Compound profit is " + trendFollowProfit + " at " + currentPeriod.getFrom() + ". " + "First price is " + currentPeriod.getPriceAtFrom() + " at " + currentPeriod.getFrom() + ". " + "Last price is " + currentPeriod.getPriceAtTo() + " at " + currentPeriod.getTo() + ". "); trendFollowProfit = trendFollowProfit * (followPriceRateOfChange + 1); if (LOGGER.isDebugEnabled()) LOGGER.debug( "New Compound at " + currentPeriod.getTo() + " : prevTotProfit*(" + followPriceRateOfChange + "+1)=" + trendFollowProfit); } else if (EventType.valueOf(currentPeriod.getTrend()).equals(EventType.BEARISH)) { // Follow Profit if (LOGGER.isDebugEnabled()) LOGGER.debug( "Sell : Compound profit is " + trendFollowProfit + " at " + currentPeriod.getFrom() + ". " + "Period " + currentPeriod + " : followPriceRateOfChange for period " + currentPeriod.getPriceRateOfChange()); } else if (EventType.valueOf(currentPeriod.getTrend()).equals(EventType.BULLISH) && !currentPeriod.isRealised()) { // Nothing if (LOGGER.isDebugEnabled()) LOGGER.debug("Unrealised bull period " + currentPeriod); } } // End for over periods // Finalise Csv file if (generateBuySellCsv) { csvWriter.close(); trendFile = fileName; } // Finalise PNG Chart if (generateSmaCmpOutChart) { try { String chartFileName = "autoPortfolioLogs" + File.separator + analyseName + stock.getSymbol() + "_" + evtDefInfo + "_OutChart" + endDateStamp + ".png"; generateOutChart(chartFileName, calcOutput, quotations, buySerie, sellSerie); observer.update( null, new ObserverMsg(stock, ObserverMsg.ObsKey.PRGSMSG, "Output images generated ...")); chartFile = chartFileName; } catch (NotEnoughDataException e) { LOGGER.warn("Can't generate chart for " + stock, e, true); chartFile = "noChartAvailable"; } catch (Exception e) { LOGGER.error("Can't generate chart for " + stock, e); chartFile = "noChartAvailable"; } } else { chartFile = "noChartAvailable"; } observer.update( null, new ObserverMsg(stock, ObserverMsg.ObsKey.PRGSMSG, "Output file generated ...")); // Output boundaries Date outputFirstKey = startDate; Date outputLastKey = endDate; if (!calcOutput.isEmpty()) { outputFirstKey = calcOutput.firstKey(); outputLastKey = calcOutput.lastKey(); } // Finalise profits trendFollowProfit = trendFollowProfit - 1; if (!periods.isEmpty()) { PeriodRatingDTO firstPeriod = periods.get(0); PeriodRatingDTO lastPeriod = periods.get(periods.size() - 1); if (lastRealisedBullIdx != -1) { Date firstBullFrom = firstPeriod.getFrom(); BigDecimal firstBullStartPrice = quotations.getClosestCloseForDate(firstBullFrom); PeriodRatingDTO lastBullPeriod = periods.get(lastRealisedBullIdx); Date lastBullTo = lastBullPeriod.getTo(); BigDecimal lastBullStartPrice = quotations.getClosestCloseForDate(lastBullTo); LOGGER.info( "Trend following compounded profit calculation is first Close " + firstBullStartPrice + " at " + firstBullFrom + " and last Close " + lastBullStartPrice + " at " + lastBullTo + " : " + trendFollowProfit); } else { LOGGER.info( "Trend following profit calculation is unknown (No bullish periods were detected or no trend change detected)"); } // Buy and hold profit BigDecimal firstClose = quotations.getClosestCloseForDate(firstPeriod.getFrom()); Double buyAndHoldProfit = (firstClose.compareTo(BigDecimal.ZERO) != 0) ? lastClose .subtract(firstClose) .divide(firstClose, 10, BigDecimal.ROUND_HALF_EVEN) .doubleValue() : Double.NaN; LOGGER.info( "Buy and hold profit calculation is first Close " + firstClose + " at " + firstPeriod.getFrom() + " and last Close " + lastClose + " at " + endDate + " : (" + lastClose + "-" + firstClose + ")/" + firstClose + "=" + buyAndHoldProfit); return new TuningResDTO( periods, trendFile, chartFile, lastPeriod.getTrend(), trendFollowProfit, Double.NaN, buyAndHoldProfit, outputFirstKey, outputLastKey); } LOGGER.info("No event detected"); return new TuningResDTO( periods, trendFile, chartFile, EventType.NONE.toString(), Double.NaN, Double.NaN, Double.NaN, outputFirstKey, outputLastKey); }
public void notifyObservers_for_selected_shape(int value) { for (Observer obs : observers) { obs.updateSelectShape(value); } }
private void notifyObservers() { for (Observer obs : observers) { obs.update(cpt); } }
private void setupUpObserverIsNotifiedOnce(Observer mockObserver) { mockObserver.update(anyObject(Observable.class), anyObject()); expectLastCall().once(); }
@Override public void close() { observer.update(null, consulta); super.close(); }
public void update() { reco.update(null, null); }
/** * Initiates an information exchange with a known and living other base if such a base exists. * * @return true if refresh was succesful, false otherwise. */ private boolean refresh() { final String logSender = observer + "#refresh"; final String contrName = ((contributor != null) ? contributor.getName() : null); // --- refreshing local contribution and commands updateLocalInfo(); // --- creating a random permutation of peers Vector peers = null; synchronized (cache) { peers = new Vector(cache.values()); // just to be sure, shouldn't be there anyway if (contrName != null) peers.remove(cache.get(contrName)); } Collections.shuffle(peers); if (peers.isEmpty()) { Logger.debug(logSender, "no peers in cache"); return false; } // --- reset array representations cacheCollection = null; commandCollection = null; // --- trying to talk to random peer IRequest answer = null; Address peer = null; for (int i = 0; i < peers.size(); ++i) { if (!shouldLive) return false; peer = ((ContributionBox) peers.get(i)).contributor; Logger.debug(logSender, "asking " + peer); answer = observer.fireMessage(peer, "collectiveUpdate-" + name, this); while (answer.getStatus() == IRequest.WAITING) { try { Thread.sleep(100); } catch (Exception e) { } } if (answer.getStatus() == IRequest.DONE) break; Logger.debug(logSender, "not accessable: " + peer); } if (answer.getStatus() != IRequest.DONE) { Logger.debug(logSender, "no accessable peers"); observer.collectiveUpdated(null); return false; } else { Collective c = (Collective) answer.getInfo("reply"); // --- remove possible garbage if (contributor != null) { cache.remove(contributor.getName()); c.cache.remove(contributor.getName()); } cache.remove(peer.name); c.cache.remove(peer.name); repairSenderAddress(c, peer); merge(c); observer.collectiveUpdated((ContributionBox) cache.get(c.myContribution.contributor.name)); return true; } }
private void setupUpdateIsCalledAtLeastOnce(Observer mockObserver) { mockObserver.update(anyObject(Observable.class), anyObject()); expectLastCall().atLeastOnce(); }
/** shuts down the UI, including db backup */ public static void shutDownUI() { // prompt for shutdown and backup options boolean do_backup = false; boolean backup_email = false; final String backupdir = Prefs.getPref(PrefName.BACKUPDIR); if (backupdir != null && !backupdir.equals("")) { String shutdown_action = Prefs.getPref(PrefName.SHUTDOWN_ACTION); if (shutdown_action.isEmpty() || SHUTDOWN_ACTION.PROMPT.toString().equals(shutdown_action)) { JRadioButton b1 = new JRadioButton(Resource.getResourceString("backup_notice") + " " + backupdir); JRadioButton b2 = new JRadioButton(Resource.getResourceString("exit_no_backup")); JRadioButton b3 = new JRadioButton(Resource.getResourceString("dont_exit")); JRadioButton b4 = new JRadioButton(Resource.getResourceString("backup_with_email")); b1.setSelected(true); ButtonGroup group = new ButtonGroup(); group.add(b1); group.add(b2); group.add(b3); group.add(b4); Object[] array = { b1, b4, b2, b3, }; int res = JOptionPane.showConfirmDialog( null, array, Resource.getResourceString("shutdown_options"), JOptionPane.OK_CANCEL_OPTION); if (res != JOptionPane.YES_OPTION) { return; } if (b3.isSelected()) return; if (b1.isSelected() || b4.isSelected()) do_backup = true; if (b4.isSelected()) backup_email = true; } else if (SHUTDOWN_ACTION.BACKUP.toString().equals(shutdown_action)) { do_backup = true; } else if (SHUTDOWN_ACTION.EMAIL.toString().equals(shutdown_action)) { do_backup = true; backup_email = true; } } // stop popup timer and destroy popups ReminderManager rm = ReminderManager.getReminderManager(); if (rm != null) rm.remove(); // show a splash screen for shutdown try { SplashScreen ban = new SplashScreen(); ban.setText(Resource.getResourceString("shutdown")); ban.setVisible(true); } catch (Exception e) { e.printStackTrace(); } // backup data if (do_backup == true) { try { ExportImport.exportToZip(backupdir, backup_email); } catch (Exception e) { Errmsg.getErrorHandler().errmsg(e); return; } } // non-UI shutdown if (shutdownListener != null) shutdownListener.update(null, null); }