org.zeromq.ZMsg Java Examples

The following examples show how to use org.zeromq.ZMsg. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SendReceiveThread.java    From sawtooth-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Used by the Stream class to send a message.
 * @param message protobuf Message
 */
public final void sendMessage(final Message message) {
  lock.lock();
  try {
    if (socket == null) {
      condition.await();
    }
  } catch (InterruptedException ie) {
    ie.printStackTrace();
  } finally {
    lock.unlock();
  }
  ZMsg msg = new ZMsg();
  msg.add(message.toByteString().toByteArray());
  msg.send(socket);
}
 
Example #2
Source File: RemoteCompleter.java    From enkan with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public int complete(String buffer, int cursor, List<CharSequence> candidates) {
    ZMsg msg = new ZMsg();
    msg.add(""); // delimiter
    msg.add(buffer);
    msg.add(Integer.toString(cursor));
    msg.send(socket);

    ZMsg response = ZMsg.recvMsg(socket);
    response.pop(); // delimiter
    while (!response.isEmpty()) {
        candidates.add(response.popString());
    }
    if (candidates.isEmpty()) return cursor;

    int delimiterPos = Math.max(buffer.lastIndexOf(' '), buffer.lastIndexOf('.'));
    if (delimiterPos > 0) {
        return delimiterPos + 1;
    } else {
        return 0;
    }
}
 
Example #3
Source File: KernelSocketsZMQ.java    From beakerx with Apache License 2.0 6 votes vote down vote up
private synchronized void sendMsg(ZMQ.Socket socket, List<Message> messages) {
  if (!isShutdown()) {
    messages.forEach(message -> {
      String header = toJson(message.getHeader());
      String parent = toJson(message.getParentHeader());
      String meta = toJson(message.getMetadata());
      String content = toJson(message.getContent());
      String digest = hmac.sign(Arrays.asList(header, parent, meta, content));

      ZMsg newZmsg = new ZMsg();
      message.getIdentities().forEach(newZmsg::add);
      newZmsg.add(DELIM);
      newZmsg.add(digest.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(header.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(parent.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(meta.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(content.getBytes(StandardCharsets.UTF_8));
      message.getBuffers().forEach(x -> newZmsg.add(x));
      newZmsg.send(socket);
    });
  }
}
 
Example #4
Source File: SendReceiveThread.java    From sawtooth-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public int handle(final ZLoop loop, final ZMQ.PollItem item, final Object arg) {
  ZMsg msg = ZMsg.recvMsg(item.getSocket());
  Iterator<ZFrame> multiPartMessage = msg.iterator();

  ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
  while (multiPartMessage.hasNext()) {
    ZFrame frame = multiPartMessage.next();
    try {
      byteArrayOutputStream.write(frame.getData());
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
  try {
    Message message = Message.parseFrom(byteArrayOutputStream.toByteArray());
    if (this.futures.containsKey(message.getCorrelationId())) {
      Future future = this.futures.get(message.getCorrelationId());
      future.setResult(message.getContent());
      this.futures.remove(message.getCorrelationId(), future);
    } else {
      MessageWrapper wrapper = new MessageWrapper(message);
      this.receiveQueue.put(wrapper);
    }
  } catch (InterruptedException ie) {
    ie.printStackTrace();
  } catch (InvalidProtocolBufferException ipe) {
    ipe.printStackTrace();
  } catch (ValidatorConnectionError vce) {
    vce.printStackTrace();
  }

  return 0;
}
 
Example #5
Source File: ZmqServerTransport.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void send(ReplResponse response) {
    ZMsg msg = new ZMsg();
    msg.add(clientAddress.duplicate());
    msg.add(fressian.write(response));
    msg.send(socket, true);
}
 
Example #6
Source File: CompletionServer.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run() {
    while(!Thread.currentThread().isInterrupted()) {
        ZMsg msg = ZMsg.recvMsg(socket);
        ZFrame clientAddress = msg.pop();
        String input = msg.popString();
        int cursor = Integer.parseInt(msg.popString());
        int[] anchor = {-1};

        ZMsg reply = new ZMsg();
        reply.add(clientAddress.duplicate());

        String trimmedCommand = input.trim();
        if (trimmedCommand.startsWith("/")) {
            if (!trimmedCommand.contains(" ")) {
                Predicate<String> filter = trimmedCommand.equals("/") ?
                        n -> true : n -> n.startsWith(trimmedCommand.substring(1));

                commandNames.stream()
                        .filter(filter)
                        .forEach(s -> reply.add("/" + s));
                anchor[0] = 0;
            }
        }
        reply.send(socket, true);
    }
}
 
Example #7
Source File: CompletionServer.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run() {
    while(!Thread.currentThread().isInterrupted()) {
        ZMsg msg = ZMsg.recvMsg(socket);
        ZFrame clientAddress = msg.pop();
        msg.pop(); // delimiter
        String input = msg.popString();
        int cursor = Integer.parseInt(msg.popString());
        int[] anchor = {-1};

        ZMsg reply = new ZMsg();
        reply.add(clientAddress.duplicate());
        reply.add("");

        String trimmedCommand = input.trim();
        if (trimmedCommand.startsWith("/")) {
            if (!trimmedCommand.contains(" ")) {
                Predicate<String> filter = trimmedCommand.equals("/") ?
                        n -> true : n -> n.startsWith(trimmedCommand.substring(1));

                commandNames.stream()
                        .filter(filter)
                        .forEach(s -> reply.add("/" + s));
                anchor[0] = 0;
            }
        } else {
            try {
                analysis.completionSuggestions(input, cursor, anchor).stream()
                        .map(SourceCodeAnalysis.Suggestion::continuation)
                        .forEach(reply::add);
                anchor[0] += cursor + 1;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        reply.send(socket, true);
    }
}
 
Example #8
Source File: ZMQIntegrationTest.java    From netty-zmtp with Apache License 2.0 5 votes vote down vote up
private void testReqRep(final ZMQ.Socket req, final ZMTPSocket rep, final String zmqIdentity)
    throws InterruptedException, TimeoutException {

  // Verify that sockets are connected
  verify(handler, timeout(5000)).connected(eq(rep), any(ZMTPSocket.ZMTPPeer.class));

  // Verify that the peer identity was correctly received
  verifyPeerIdentity(rep, zmqIdentity);

  // Send request
  final ZMsg request = ZMsg.newStringMsg("envelope", "", "hello", "world");
  request.send(req, false);

  // Receive request
  verify(handler, timeout(5000)).message(
      eq(rep), any(ZMTPSocket.ZMTPPeer.class), messageCaptor.capture());
  final ZMTPMessage receivedRequest = messageCaptor.getValue();

  // Send reply
  rep.send(receivedRequest);

  // Receive reply
  final ZMsg reply = ZMsg.recvMsg(req);

  // Verify echo
  assertEquals(request, reply);
}
 
Example #9
Source File: ZMQIntegrationTest.java    From netty-zmtp with Apache License 2.0 5 votes vote down vote up
private void testReqRep(final ZMTPSocket req, final ZMQ.Socket rep, final String zmqIdentity)
    throws InterruptedException, TimeoutException {

  // Verify that sockets are connected
  verify(handler, timeout(5000)).connected(eq(req), any(ZMTPSocket.ZMTPPeer.class));

  // Verify that the peer identity was correctly received
  verifyPeerIdentity(req, zmqIdentity);

  // Send request
  final ZMTPMessage request = ZMTPMessage.fromUTF8("envelope", "", "hello", "world");
  request.retain();
  req.send(request);

  // Receive request
  final ZMsg receivedRequest = ZMsg.recvMsg(rep);

  // Send reply
  receivedRequest.send(rep, false);

  // Receive reply
  verify(handler, timeout(5000)).message(
      eq(req), any(ZMTPSocket.ZMTPPeer.class), messageCaptor.capture());
  final ZMTPMessage reply = messageCaptor.getValue();
  ReferenceCountUtil.releaseLater(reply);

  // Verify echo
  assertEquals(request, reply);
  request.release();
}
 
Example #10
Source File: ZeroMQEventSubscriber.java    From support-rulesengine with Apache License 2.0 4 votes vote down vote up
public void receive() {
	getSubscriber();
	JsonNode node;
	ZMsg zmsg;
	ZFrame[] parts;
	logger.info("Watching for new exported Event messages...");
	try {
		while (!Thread.currentThread().isInterrupted()) {
			zmsg = ZMsg.recvMsg(subscriber);
			parts = new ZFrame[zmsg.size()];
			zmsg.toArray(parts);
			logger.debug("Message has " + parts.length + " parts.");

			if (parts.length < 2) {// if the message is not a multi-part message
				try {
					node = mapper.readTree(parts[0].getData());
				} catch (JsonProcessingException jsonE) {  // if can't parse the data from the message, assume it is CBOR
					processCborEvent(parts[0]);
					break;
				}
			} else // if the message is multi-part message
				node = mapper.readTree(parts[1].getData());
			switch (payloadType(node)) {
			case NO_ENVELOPE:
				processEvent(node);
				break;
			case JSON:
				processJsonEvent(node);
				break;
			case CBOR:
				processCborEvent(node);
				break;
			default:
				logger.error("Unknown payload type received");
				break;
			}
		}
	} catch (Exception e) {
		logger.error("Unable to receive messages via ZMQ: " + e.getMessage());
	}
	logger.error("Shutting off Event message watch due to error!");
	if (subscriber != null)
		subscriber.close();
	subscriber = null;
	// try to restart
	logger.debug("Attempting restart of Event message watch.");

	receive();

}
 
Example #11
Source File: ZmqServerTransport.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public String recv(long timeout) {
    ZMsg msg = ZMsg.recvMsg(socket);
    clientAddress = msg.pop();
    return msg.popString();
}
 
Example #12
Source File: MessageObject.java    From jupyter-kernel-jsr223 with Apache License 2.0 4 votes vote down vote up
public MessageObject(ZMsg zmsg, Socket socket, byte[] key) {
    this.socket = socket;
    this.key = key;
    this.zmsg = zmsg;
    this.msg = new T_message();
}
 
Example #13
Source File: Session.java    From jupyter-kernel-jsr223 with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    MessageObject msg;
    if (!createSockets()) {
        return;
    }
    try {
        kernel.setStdinTemplate(new MessageObject(null, Stdin, key));
        kernel.setIOPubTemplate(new MessageObject(null, IOPub, key));
        kernel.setConnectionData(connectionData);
        System.out.println(
                String.format("[jupyter-kernel.jar] %s kernel started.", 
                        kernel.getKernel())
        );
        while (!this.isInterrupted()) {
            byte[] message;
            sockets.poll();
            if (sockets.pollin(0)) {
                msg = new MessageObject(ZMsg.recvMsg(Control), Control, key);
                kernel.dispatch(msg);
            }
            if (sockets.pollin(1)) {
                message = Heartbeat.recv(0);
                Heartbeat.send(message);
            }
            if (sockets.pollin(2)) {
                msg = new MessageObject(ZMsg.recvMsg(Shell), Shell, key);
                kernel.dispatch(msg);
            }
            if (sockets.pollin(3)) {
                msg = new MessageObject(ZMsg.recvMsg(Stdin), Stdin, key);
                kernel.dispatch(msg);
            }
            if (kernel.isShutdownRequested()) {
                restart_kernel_requested = kernel.isRestartRequested();
                break;
            }
        }
    } finally {
        closeSockets();
    }
}