/** * Subscribes a given Subscriber with the given subscription type * * @param subscriber The given Subscriber object * @param type Type of subscription * @return Returns true if the subscription was successfully applied for the given type */ public boolean subscribe(Subscriber subscriber, String type) { boolean flag = false; if (subscriber != null && type != null) { for (Publisher pub : publishers) { if (pub.getPublisher().getType().contains(type)) { flag = true; break; } } if (!flag) return false; NewSubscriber newSubscriber = subscriber.getSubscriber(); ArrayList<String> temp = subscriberMap.get(newSubscriber); if (temp != null) { if (temp.contains(type)) return false; subscriberMap.get(newSubscriber).add(type); return true; } else { ArrayList<String> tempType = new ArrayList<String>(); tempType.add(type); subscriberMap.put(newSubscriber, tempType); return true; } } return false; }
private static void setUp() { final User user1 = new User("Luca", "Molteni", "lmolteni", "*****@*****.**"); final User user2 = new User("User2", "Surname2", "account2", "*****@*****.**"); final Publisher p1 = new Publisher("All the cool CS books", "San Francisco CA"); final Book b1 = new Book("Java Persistence With Hibernate", 23l, "Gavin King"); final Book b2 = new Book("The C Programming Language ", 30l, "Brian Kerninghan"); p1.addBook(b1); p1.addBook(b2); final Purchase purch1 = new Purchase(user1, b1, 10l); final Purchase purch2 = new Purchase(user1, b2, 20l); final Purchase purch3 = new Purchase(user2, b2, 15l); final EntityManager em = EntityManagerBean.getEntityManager(); final EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(user1); em.persist(user2); em.persist(p1); em.persist(b1); em.persist(b2); em.persist(purch1); em.persist(purch2); em.persist(purch3); tx.commit(); em.close(); }
@Test public void testOneSubscriberReceivesAMessage() { final Subscriber subscriber = context.mock(Subscriber.class); final String message = "message"; context.checking( new Expectations() { { // never(subscriber).receive(message); oneOf(subscriber).receive(message); // exactly(1).of(subscriber).receive(message); // atLeast(1).of(subscriber).receive(message); // atMost(2).of(subscriber).receive(message); // between(1, 5).of(subscriber).receive(message); // allowing(subscriber).receive(message); will(returnValue("Hello world")); } }); Publisher publisher = new Publisher(); publisher.add(subscriber); // execute String answer = publisher.publish(message); // verify context.assertIsSatisfied(); Assert.assertEquals("Hello world", answer); }
/** * Adds the given Publisher to the system. * * @param pub The given Publisher object * @return Returns true if the Publisher was added successfully else return false */ public boolean addPublisher(Publisher pub) { if (pub == null || pub.getPublisher().getType() == null || pub.getPublisher().getType().contains(null)) return false; return publishers.add(pub.getPublisher()); }
private void publish(IConfig config, File dir) throws Exception { String clazz = config.getString("class", null); Publisher publisher = null; if (clazz == null) publisher = new PathPublisher(); else publisher = getAqua().createPublisher(clazz); publisher.publish(config, dir); }
public static void main(String[] args) { Subscriber subscriber = new Subscriber(); subscriber.subscribe("FastMovingStockQuotes"); Publisher publisher = new Publisher(); publisher.publishMessages("AllStockQuotes"); subscriber.unsubscribe(); }
/** * Default bus initialization with only one handler, the default publisher * * @param addr * @param addrSync */ public BusGuavaImpl(final String addr, final String addrSync) { Publisher pub = new PublisherZMQImpl(); pub.open(addr, addrSync); channel.register(pub); logger.info( "Bus initialized (publisher open with address={} and synchronization address={}, and publisher register to the channel={})", new Object[] {addr, addrSync, CHANNEL_NAME}); }
@Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validateSubscription(this.s, s)) { return; } this.s = s; Subscriber<? super U> actual = this.actual; U b; try { b = bufferSupplier.get(); } catch (Throwable e) { cancelled = true; s.cancel(); EmptySubscription.error(e, actual); return; } if (b == null) { cancelled = true; s.cancel(); EmptySubscription.error(new NullPointerException("The buffer supplied is null"), actual); return; } buffer = b; Publisher<B> boundary; try { boundary = boundarySupplier.get(); } catch (Throwable ex) { cancelled = true; s.cancel(); EmptySubscription.error(ex, actual); return; } if (boundary == null) { cancelled = true; s.cancel(); EmptySubscription.error( new NullPointerException("The boundary publisher supplied is null"), actual); return; } BufferBoundarySubscriber<T, U, B> bs = new BufferBoundarySubscriber<T, U, B>(this); other = bs; actual.onSubscribe(this); if (!cancelled) { s.request(Long.MAX_VALUE); boundary.subscribe(bs); } }
void next() { Disposable o = other; U next; try { next = bufferSupplier.get(); } catch (Throwable e) { cancel(); actual.onError(e); return; } if (next == null) { cancel(); actual.onError(new NullPointerException("The buffer supplied is null")); return; } Publisher<B> boundary; try { boundary = boundarySupplier.get(); } catch (Throwable ex) { cancelled = true; s.cancel(); actual.onError(ex); return; } if (boundary == null) { cancelled = true; s.cancel(); actual.onError(new NullPointerException("The boundary publisher supplied is null")); return; } BufferBoundarySubscriber<T, U, B> bs = new BufferBoundarySubscriber<T, U, B>(this); if (!OTHER.compareAndSet(this, o, bs)) { return; } U b; synchronized (this) { b = buffer; if (b == null) { return; } buffer = next; } boundary.subscribe(bs); fastpathEmitMax(b, false, this); }
/** * Attempts to execute a command and adds it to the undo stack if the command executes * successfully. * * @param command The command to execute. */ void executeCommand(Command command) { boolean success = command.execDo(); // Only mess with the command stacks if the command was executed // successfully. if (success) { // If the command invalidates the command stacks then // clear the command stacks. if (command.invalidates()) { undoStack.clear(); redoStack.clear(); } // If the command is undoable, it must be added to the undo // stack and the redo stack must be cleared. if (command.isUndoable()) { undoStack.addLast(command); if (undoStack.size() > mThreshold) { undoStack.removeFirst(); } redoStack.clear(); } // Necessary so that the undo/redo menu gets an update // AFTER the command has successfully executed. publisher.publishEvent(new Event()); } }
private void fireTimeout() { publisher.publish( new Distributor<KioskModeHandler.Listener>() { @Override public void deliverTo(Listener subscriber) { subscriber.notifyTimedOut(); } }); }
@Test public void testBPubSub() throws InterruptedException { String topic = "test"; // Start pubsub server Server server = new Server("127.0.0.1", Settings.CLIENT_SUBSCRIBE_PORT, Settings.CLIENT_PUBLISH_PORT); server.start(); // Create publisher and subscriber Publisher publisher = new Publisher("127.0.0.1", Settings.CLIENT_PUBLISH_PORT); Subscriber subscriber = new Subscriber("127.0.0.1", Settings.CLIENT_SUBSCRIBE_PORT); // Subscribe to test topic TestPubSubCallback cb = new TestPubSubCallback(); subscriber.subscribe(topic, cb); Thread.sleep(1000); // Publish a message System.out.println("Publisher publishing " + "hello" + " on topic " + topic); publisher.publish(topic, PubSubProtos.StringMessage.newBuilder().setMessage("hello").build()); cb.awaitMessage("hello"); // Publish a message System.out.println("Publisher publishing " + "hello" + " on topic " + "badtest"); publisher.publish( "badtest", PubSubProtos.StringMessage.newBuilder().setMessage("hello").build()); cb.awaitNoMessage("hello"); // Publish a message System.out.println("Publisher publishing " + "hello2" + " on topic " + topic); publisher.publish(topic, PubSubProtos.StringMessage.newBuilder().setMessage("hello2").build()); cb.awaitMessage("hello2"); // Unsubscribe subscriber.unsubscribe(topic, cb); Thread.sleep(1000); // Publish a message System.out.println("Publisher publishing " + "hello2" + " on topic " + topic); publisher.publish(topic, PubSubProtos.StringMessage.newBuilder().setMessage("hello2").build()); cb.awaitNoMessage("hello2"); }
public static void main(String[] args) throws XMPPException { /** Erzeugen von Instanzen */ NodeService service = new NodeService(); Publisher pub = new Publisher(); Subscriber sub = new Subscriber(); /** NodeService erstellt/löscht/verändert Knoten und lässt sich Informationen ausgeben */ service.connect(ups); service.getNodes(); service.printNode("Bruno"); System.out.println(""); service.disconnect(); System.out.println(""); /** * Subscriber prüft nach neuen Nachrichten * * <p>Publisher löscht/erstellt neue Nachricht */ pub.connect(u1); pub.deleteMessage("1", "Bruno"); pub.addPayloadMessage("1", "Bruno"); pub.disconnect(); System.out.println(""); /* * Subscriber lässt sich alle Knoten ausgeben und abonniert einen Knoten */ sub.connect(u3); sub.getNodes(); sub.abonnieren("Bruno", u3); sub.disconnect(); System.out.println(""); /** NodeService lässt sich Infomationen ausgeben */ service.connect(ups); service.printNode("Bruno"); service.disconnect(); }
/** @param args */ public static void main(String[] args) { Publisher p = new Publisher(); p.addMusic("Musik0"); p.addMusic("Musicx"); p.addMusic("Musik1"); p.addMusic("Musik2"); p.addMusic("Musik3"); p.addMusic("Musik4"); p.addMusic("Musik5"); p.addMusic("Musik6"); p.addMusic("Musik7"); p.addMusic("Musik8"); p.addMusic("Musik9"); Subscriber s1 = new Subscriber("sub1"); Subscriber s2 = new Subscriber("sub2"); p.addSubscriber(s1); p.addSubscriber(s2); p.notifySubscribers(); p.removeMusic("Musik0"); p.removeMusic("Musicx"); }
/** * Import publishers * * @param nodes * @return */ private Boolean processPublishers(NodeList nodes) { NodeList publishers = nodes.item(0).getChildNodes(); for (int i = 0; i < publishers.getLength(); i++) { if (publishers.item(i).getNodeType() == Node.ELEMENT_NODE) { Element publisherNode = (Element) publishers.item(i); Publisher publisher = new Publisher(); publisher.setIdpublisher(Integer.parseInt(getTagValue("idpublisher", publisherNode))); publisher.setName(getTagValue("name", publisherNode)); publisher.setAddress(getTagValue("address", publisherNode)); try { publisherMgr.save(publisher); } catch (EJBException ex) { ex.printStackTrace(System.out); } } } return true; }
/** * Attempts to redo the first command in the redo stack, and adds it to the undo stack if * successful. */ void redoCommand() { if (!redoStack.isEmpty()) { Command command = redoStack.removeLast(); boolean success = command.execDo(); if (success) { undoStack.addLast(command); } // Necessary so that the undo/redo menu gets an update // AFTER the command has successfully executed. publisher.publishEvent(new Event()); } }
/** * Publishes the given message from Publisher * * @param publisherName The given Publisher object * @param messageDetails Message to be published * @return Returns true if the subscription of the type <b>type</b> was removed successfully else * returns false */ public boolean publishMessage(Publisher publisherName, Message messageDetails) { if (publisherName != null && messageDetails != null) { NewPublisher publisher = publisherName.getPublisher(); if (!publishers.contains(publisher)) { return false; } for (Subscriber sub : subscriberMap.keySet()) { if (subscriberMap .get(sub) .contains(messageDetails.getMessage().getMetadata().getMessageType())) { sub.getSubscriber().receivedMessage(messageDetails); } } } return false; }
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { super.submit(req, rsp); JSONObject json = req.getSubmittedForm(); rootPOM = Util.fixEmpty(req.getParameter("rootPOM").trim()); if (rootPOM != null && rootPOM.equals("pom.xml")) rootPOM = null; // normalization goals = Util.fixEmpty(req.getParameter("goals").trim()); alternateSettings = Util.fixEmpty(req.getParameter("alternateSettings").trim()); mavenOpts = Util.fixEmpty(req.getParameter("mavenOpts").trim()); mavenName = req.getParameter("maven_version"); aggregatorStyleBuild = !req.hasParameter("maven.perModuleBuild"); usePrivateRepository = req.hasParameter("maven.usePrivateRepository"); ignoreUpstremChanges = !json.has("triggerByDependency"); incrementalBuild = req.hasParameter("maven.incrementalBuild"); archivingDisabled = req.hasParameter("maven.archivingDisabled"); reporters.rebuild(req, json, MavenReporters.getConfigurableList()); publishers.rebuild(req, json, BuildStepDescriptor.filter(Publisher.all(), this.getClass())); buildWrappers.rebuild(req, json, BuildWrappers.getFor(this)); }
/* * Check to see if an existing repository already has the "compressed" flag set */ protected void initializeRepositories(PublisherInfo publisherInfo) throws ProvisionException { try { if (metadataLocation != null) { // Try to load the metadata repository. If it loads, check the "compressed" flag, and cache // it. // If there are any errors loading it (i.e. it doesn't exist), just skip this step // If there are serious problems with the repository, the superclass initializeRepositories // method // will handle it. IMetadataRepository result = Publisher.loadMetadataRepository(agent, metadataLocation, true, true); if (result != null) { Object property = result.getProperties().get(IRepository.PROP_COMPRESSED); if (property != null) { boolean compressProperty = Boolean.valueOf((String) property); this.compress = compressProperty || compress; } } } } catch (ProvisionException e) { // do nothing } super.initializeRepositories(publisherInfo); }
/** * Removes the given Publisher from the system. * * @param pub The given Publisher object * @return Returns true if the Publisher was removed successfully else returns false */ public boolean removePublisher(Publisher pub) { if (pub == null || pub.getPublisher() == null) return false; return publishers.remove(pub.getPublisher()); }
/** * Generates an Unpublish bundle for a given bundle id operation (publish/unpublish) * * @param bundleId The Bundle id of the Bundle we want to generate * @param operation Download for publish or un-publish * @return The generated requested Bundle file * @throws DotPublisherException If fails retrieving the Bundle contents * @throws DotDataException If fails finding the system user * @throws DotPublishingException If fails initializing the Publisher * @throws IllegalAccessException If fails creating new Bundlers instances * @throws InstantiationException If fails creating new Bundlers instances * @throws DotBundleException If fails generating the Bundle * @throws IOException If fails compressing the all the Bundle contents into the final Bundle file */ @SuppressWarnings("unchecked") private Map<String, Object> generateBundle( String bundleId, PushPublisherConfig.Operation operation) throws DotPublisherException, DotDataException, DotPublishingException, IllegalAccessException, InstantiationException, DotBundleException, IOException { PushPublisherConfig pconf = new PushPublisherConfig(); PublisherAPI pubAPI = PublisherAPI.getInstance(); List<PublishQueueElement> tempBundleContents = pubAPI.getQueueElementsByBundleId(bundleId); List<PublishQueueElement> assetsToPublish = new ArrayList<PublishQueueElement>(); // all assets but contentlets for (PublishQueueElement c : tempBundleContents) { if (!c.getType().equals("contentlet")) { assetsToPublish.add(c); } } pconf.setDownloading(true); pconf.setOperation(operation); // all types of assets in the queue but contentlets are passed here, which are passed through // lucene queries pconf.setAssets(assetsToPublish); // Queries creation pconf.setLuceneQueries(PublisherUtil.prepareQueries(tempBundleContents)); pconf.setId(bundleId); pconf.setUser(APILocator.getUserAPI().getSystemUser()); // BUNDLERS List<Class<IBundler>> bundlers = new ArrayList<Class<IBundler>>(); List<IBundler> confBundlers = new ArrayList<IBundler>(); Publisher publisher = new PushPublisher(); publisher.init(pconf); // Add the bundles for this publisher for (Class clazz : publisher.getBundlers()) { if (!bundlers.contains(clazz)) { bundlers.add(clazz); } } // Create a new bundle id for this generated bundle String newBundleId = UUID.randomUUID().toString(); pconf.setId(newBundleId); File bundleRoot = BundlerUtil.getBundleRoot(pconf); // Run bundlers BundlerUtil.writeBundleXML(pconf); for (Class<IBundler> c : bundlers) { IBundler bundler = c.newInstance(); confBundlers.add(bundler); bundler.setConfig(pconf); BundlerStatus bundlerStatus = new BundlerStatus(bundler.getClass().getName()); // Generate the bundler bundler.generate(bundleRoot, bundlerStatus); } pconf.setBundlers(confBundlers); // Compressing bundle ArrayList<File> list = new ArrayList<File>(); list.add(bundleRoot); File bundle = new File(bundleRoot + File.separator + ".." + File.separator + pconf.getId() + ".tar.gz"); Map<String, Object> bundleData = new HashMap<String, Object>(); bundleData.put("id", newBundleId); bundleData.put("file", PushUtils.compressFiles(list, bundle, bundleRoot.getAbsolutePath())); return bundleData; }
public void addListener(Listener listener) { publisher.subscribe(listener); }
public static void main(String[] args) throws InterruptedException, FileNotFoundException { brokerIP = args[0]; numIterations = Integer.parseInt(args[1]); endpointName = "TestPubSub"; ConnectionFactory.initialize(endpointName); numSubscribers = topicHierarchies.length; ExecutorService executor = Executors.newFixedThreadPool(numSubscribers); CountDownLatch startSignal = new CountDownLatch(1); CountDownLatch doneSignal = new CountDownLatch(numSubscribers); TestSubscriber[] subscribers = new TestSubscriber[numSubscribers]; for (int i = 0; i < numSubscribers; i++) { TestSubscriber subscriber = new TestSubscriber(startSignal, doneSignal, i); subscribers[i] = subscriber; executor.submit(subscriber); } startSignal.countDown(); Thread.sleep(10000); Session session = ConnectionFactory.createSession(brokerIP); Publisher publisher = session.createHierarchicalTopicPublisher("root"); final AtomicInteger messageAckCount = new AtomicInteger(0); publisher.registerMessageAckReceiver( new DoveMQMessageAckReceiver() { @Override public void messageAcknowledged(DoveMQMessage message) { messageAckCount.incrementAndGet(); } }); System.out.println("created publisher"); int messagesSent = 0; Random randomGenerator = new Random(); for (int iter = 0; iter < numIterations; iter++) { for (String hierarchy : publishTopicHierarchies) { DoveMQMessage message = EndpointTestUtils.createEncodedMessage(randomGenerator, true); message.setTopicPublishHierarchy(hierarchy); publisher.publishMessage(message); messagesSent++; if (messagesSent % 10000 == 0) { System.out.println("Sent message count: " + messagesSent); } } } for (String hierarchy : shutdownMessageHierarchies) { DoveMQMessage message = MessageFactory.createMessage(); message.addPayload("TOPIC_TEST_DONE".getBytes()); message.setTopicPublishHierarchy(hierarchy); publisher.publishMessage(message); messagesSent++; } while (messageAckCount.get() < messagesSent) { try { Thread.sleep(5000); System.out.println("publisher waiting: " + messagesSent + " " + messageAckCount.get()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } doneSignal.await(); assertTrue(subscribers[0].numMessagesReceived() == 14 * numIterations); assertTrue(subscribers[1].numMessagesReceived() == 7 * numIterations); assertTrue(subscribers[2].numMessagesReceived() == 4 * numIterations); assertTrue(subscribers[3].numMessagesReceived() == 2 * numIterations); assertTrue(subscribers[4].numMessagesReceived() == 2 * numIterations); assertTrue(subscribers[5].numMessagesReceived() == 6 * numIterations); assertTrue(subscribers[6].numMessagesReceived() == 2 * numIterations); assertTrue(subscribers[7].numMessagesReceived() == 2 * numIterations); assertTrue(subscribers[8].numMessagesReceived() == 1 * numIterations); Thread.sleep(2000); executor.shutdown(); ConnectionFactory.shutdown(); }
public void removeListener(Listener listener) { publisher.unsubscribe(listener); }
@Override public void onMessage(byte[] buffer, int offset, int size) { if (ignore) { return; } Tuple request = Tuple.getTuple(buffer, offset, size); switch (request.getType()) { case PUBLISHER_REQUEST: /* * unregister the unidentified client since its job is done! */ unregistered(key); logger.info("Received publisher request: {}", request); PublishRequestTuple publisherRequest = (PublishRequestTuple) request; DataList dl = handlePublisherRequest(publisherRequest, this); dl.setAutoFlushExecutor(serverHelperExecutor); Publisher publisher; if (publisherRequest.getVersion().equals(Tuple.FAST_VERSION)) { publisher = new Publisher(dl, (long) request.getBaseSeconds() << 32 | request.getWindowId()) { @Override public int readSize() { if (writeOffset - readOffset < 2) { return -1; } short s = buffer[readOffset++]; return s | (buffer[readOffset++] << 8); } }; } else { publisher = new Publisher(dl, (long) request.getBaseSeconds() << 32 | request.getWindowId()); } key.attach(publisher); key.interestOps(SelectionKey.OP_READ); publisher.registered(key); int len = writeOffset - readOffset - size; if (len > 0) { publisher.transferBuffer(this.buffer, readOffset + size, len); } ignore = true; break; case SUBSCRIBER_REQUEST: /* * unregister the unidentified client since its job is done! */ unregistered(key); ignore = true; logger.info("Received subscriber request: {}", request); SubscribeRequestTuple subscriberRequest = (SubscribeRequestTuple) request; AbstractLengthPrependerClient subscriber; // /* for backward compatibility - set the buffer size to 16k - EXPERIMENTAL */ int bufferSize = subscriberRequest.getBufferSize(); // if (bufferSize == 0) { // bufferSize = 16 * 1024; // } if (subscriberRequest.getVersion().equals(Tuple.FAST_VERSION)) { subscriber = new Subscriber( subscriberRequest.getStreamType(), subscriberRequest.getMask(), subscriberRequest.getPartitions(), bufferSize); } else { subscriber = new Subscriber( subscriberRequest.getStreamType(), subscriberRequest.getMask(), subscriberRequest.getPartitions(), bufferSize) { @Override public int readSize() { if (writeOffset - readOffset < 2) { return -1; } short s = buffer[readOffset++]; return s | (buffer[readOffset++] << 8); } }; } key.attach(subscriber); key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ); subscriber.registered(key); final LogicalNode logicalNode = handleSubscriberRequest(subscriberRequest, subscriber); serverHelperExecutor.submit( new Runnable() { @Override public void run() { logicalNode.catchUp(); } }); break; case PURGE_REQUEST: logger.info("Received purge request: {}", request); try { handlePurgeRequest((PurgeRequestTuple) request, this); } catch (IOException io) { throw new RuntimeException(io); } break; case RESET_REQUEST: logger.info("Received reset all request: {}", request); try { handleResetRequest((ResetRequestTuple) request, this); } catch (IOException io) { throw new RuntimeException(io); } break; default: throw new RuntimeException("unexpected message: " + request.toString()); } }
public static void main(String[] args) { Publisher app = new Publisher(); int status = app.main("Publisher", args, "config.pub"); System.exit(status); }