org.zeromq.ZFrame Java Examples

The following examples show how to use org.zeromq.ZFrame. 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 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 #2
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 #3
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 #4
Source File: KernelSocketsZMQ.java    From beakerx with Apache License 2.0 5 votes vote down vote up
private String verifyDelim(ZFrame zframe) {
  String delim = new String(zframe.getData(), StandardCharsets.UTF_8);
  if (!DELIM.equals(delim)) {
    throw new RuntimeException("Delimiter <IDS|MSG> not found");
  }
  return delim;
}
 
Example #5
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 #6
Source File: ZmqServerTransport.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
public ZmqServerTransport(Socket socket, ZFrame clientAddress) {
    this.socket = socket;
    this.clientAddress = clientAddress;
}
 
Example #7
Source File: ZmqServerTransport.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
public ZFrame getClientAddress() {
    return clientAddress;
}
 
Example #8
Source File: JShellIoProxy.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
public ZmqServerTransport listen(ZMQ.Socket socket, ZFrame clientAddress) {
    return transports.computeIfAbsent(clientAddress,
            addr -> new ZmqServerTransport(socket, addr));
}
 
Example #9
Source File: JShellIoProxy.java    From enkan with Eclipse Public License 1.0 4 votes vote down vote up
public void unlisten(ZFrame clientAddress) {
    ZmqServerTransport transport = transports.remove(clientAddress);
    transport.close();
}
 
Example #10
Source File: MessageObject.java    From jupyter-kernel-jsr223 with Apache License 2.0 4 votes vote down vote up
public void read() {
    try {
        ZFrame[] zframes = new ZFrame[zmsg.size()];
        zmsg.toArray(zframes);
        if (zmsg.size() < 7) {
            throw new RuntimeException("[jupyter-kernel.jar] Message incomplete. Didn't receive required message parts");
        }
        uuid = zframes[MessageParts.UUID].getData();
        String delim = new String(zframes[MessageParts.DELIM].getData(), 
                                  StandardCharsets.UTF_8);
        if (!delim.equals(delimiter)) {
            throw new RuntimeException("[jupyter-kernel.jar] Incorrectly formatted message. Delimiter <IDS|MSG> not found");
        }                        
        byte[] header = zframes[MessageParts.HEADER].getData();
        byte[] parent = zframes[MessageParts.PARENT].getData();
        byte[] meta = zframes[MessageParts.METADATA].getData();
        byte[] content = zframes[MessageParts.CONTENT].getData();

        byte[] digest = computeSignature(header, parent, meta, content);
        byte[] hmac = zframes[MessageParts.HMAC].getData();
        // hmac is an UTF-8 string and has to be converted into a byte array first
        hmac = HexBinaryConverter.parseHexBinary(new String(hmac));
        
        mildlySecureMACCompare(digest, hmac);
        
        JSONObject jsonHeader = new JSONObject(new String(header, StandardCharsets.UTF_8));
        if(null == T_JSON.message_protocol_version)
        {
            String protocolVersion = (String)jsonHeader.get("version");
            checkAllowedProtocolVersion(protocolVersion);
            // set protocol version for protocol specific serialization / deserialization
            T_JSON.setProtocolVersion(protocolVersion);
        }
        msg.header = (T_header)T_JSON.fromJSON("T_header", jsonHeader);                    
        msg.parent_header = (T_header)T_JSON.fromJSON("T_header", 
                new JSONObject(new String(parent, StandardCharsets.UTF_8)));
        msg.metadata = new JSONObject(new String(meta, StandardCharsets.UTF_8));
        msg.content = T_JSON.fromJSON("T_"+msg.header.msg_type, 
                new JSONObject(new String(content, StandardCharsets.UTF_8)));
        
    } finally {
        zmsg.destroy();
    }
}