org.msgpack.type.Value Java Examples

The following examples show how to use org.msgpack.type.Value. 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: Future.java    From msgpack-rpc-java with Apache License 2.0 6 votes vote down vote up
public V getResult() {
    Value result = impl.getResult();
    if (resultTemplate == null) {
        return (V) result;
    } else if (result.isNilValue()) {
        return null;
    } else {
        try {
            return (V) resultTemplate.read(
                    new Converter(messagePack, result), null);
            // return (V)messagePack.c(result,);
            // result.convert(resultTemplate);
        } catch (IOException e) {
            return null;
        }
    }
}
 
Example #2
Source File: GeneralMesseageConsumer.java    From laser with Apache License 2.0 6 votes vote down vote up
private boolean setItemProfile(String title, Vector profile) {
	try {
		Object[] req = new Object[1];
		req[0] = title;
		Value res = msgpackClient.read(req, "splitTitle");
		Converter converter = new org.msgpack.unpacker.Converter(res);
		SparseVector vec = converter.read(SparseVector.class);
		converter.close();

		while (vec.hasNext()) {
			profile.set(vec.getIndex(), vec.get());
		}
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
Example #3
Source File: LaserOfflineTopNDriver.java    From laser with Apache License 2.0 6 votes vote down vote up
public static int serializeClusteringInfo(Path path, String urlList,
		Integer port, Configuration conf) throws IOException {
	FileSystem fs = path.getFileSystem(conf);
	if (fs.exists(path)) {
		return 0;
	}
	
	MsgpackClient client = new MsgpackClient(urlList, port, conf.get("com.b5m.msgpack.collection"));
	client.setTimeout(1000);
	Value res = client.read(new Object[0], "getClusteringInfos");
	AdClusteringsInfo response = new org.msgpack.unpacker.Converter(
			new MessagePack(), res).read(AdClusteringsInfo.class);

	DataOutputStream out = fs.create(path);
	response.write(out);
	out.close();
	return 0;
}
 
Example #4
Source File: FutureImpl.java    From msgpack-rpc-java with Apache License 2.0 6 votes vote down vote up
public void setResult(Value result, Value error) {
    synchronized (lock) {
        if (done) {
            return;
        }
        this.result = result;
        this.error = error;
        this.done = true;
        lock.notifyAll();
    }
    if (callback != null) {
        // FIXME #SF submit?
        // session.getEventLoop().getWorkerExecutor().submit(callback);
        callback.run();
    }
}
 
Example #5
Source File: MessagePackMarshallingStrategy.java    From ob1k with Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> T unmarshall(final Type type, final Response response) throws IOException {

  final int statusCode = response.getStatusCode();

  if (statusCode < 200 || statusCode >= 300) {
    log.debug("request fail, status code: {}", statusCode, response);
    throw new IOException("Call failed for url: " + response.getUrl() + ", status code: " + statusCode + ".\n" +
            response.getResponseBody());
  }

  if (HttpResponseStatus.NO_CONTENT.code() == statusCode || !response.hasResponseBody()) {
    // on empty body the object mapper throws "JsonMappingException: No content to map due to end-of-input"
    return null;
  }

  final Value value = messagePack.read(response.getResponseBodyAsBytes());
  final Template<T> template = (Template<T>) messagePack.lookup(type);
  return template.read(new Converter(messagePack, value), null);
}
 
Example #6
Source File: RpcMessageHandler.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public void handleMessage(MessageSendable channel, Value msg) {
    if (useThread) {
        loop.getWorkerExecutor().submit(
                new HandleMessageTask(this, channel, msg));
    } else {
        handleMessageImpl(channel, msg);
    }
}
 
Example #7
Source File: RemoteError.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
private static String loadMessage(Value data) {
    try {
        if (data.isRawValue()) {
            return data.asRawValue().getString();
        } else {
            return data.asArrayValue().getElementArray()[0].asRawValue().getString();
        }
    } catch (MessageTypeException e) {
        return "unknown error: " + data;
    }
}
 
Example #8
Source File: Server.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public void onNotify(String method, Value args) {
    Request request = new Request(method, args);
    try {
        dp.dispatch(request);
    } catch (Exception e) {
        // FIXME ignore?
    }
}
 
Example #9
Source File: Session.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public Future<Value> sendRequest(String method, Object[] args) {
    int msgid = seqid.getAndAdd(1);
    RequestMessage msg = new RequestMessage(msgid, method, args);
    FutureImpl f = new FutureImpl(this);

    synchronized (reqtable) {
        reqtable.put(msgid, f);
    }
    transport.sendMessage(msg);

    return new Future<Value>(loop.getMessagePack(), f);
}
 
Example #10
Source File: Session.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public void onResponse(int msgid, Value result, Value error) {
    FutureImpl f;
    synchronized (reqtable) {
        f = reqtable.remove(msgid);
    }
    if (f == null) {
        // FIXME log
        return;
    }
    f.setResult(result, error);
}
 
Example #11
Source File: MessageHandler.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
    Object m = e.getMessage();
    if (!(m instanceof Value)) {
        ctx.sendUpstream(e);
        return;
    }

    Value msg = (Value) m;
    handler.handleMessage(adaptor, msg);
}
 
Example #12
Source File: MessagePackStreamDecoder.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer source) throws Exception {
    // TODO #MN will modify the body with MessagePackBufferUnpacker.
    ByteBuffer buffer = source.toByteBuffer();
    if (!buffer.hasRemaining()) {
        return null;
    }
    source.markReaderIndex();

    byte[] bytes = buffer.array(); // FIXME buffer must has array
    int offset = buffer.arrayOffset() + buffer.position();
    int length = buffer.arrayOffset() + buffer.limit();
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes, offset,
            length);
    int startAvailable = stream.available();
    try{
        Unpacker unpacker = msgpack.createUnpacker(stream);
        Value v = unpacker.readValue();
        source.skipBytes(startAvailable - stream.available());
        return v;
    }catch( EOFException e ){
        // not enough buffers.
        // So retry reading
        source.resetReaderIndex();
        return null;
    }
}
 
Example #13
Source File: MessagePackDecoder.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        Object msg) throws Exception {
    if (!(msg instanceof ChannelBuffer)) {
        return msg;
    }

    ChannelBuffer source = (ChannelBuffer) msg;

    ByteBuffer buffer = source.toByteBuffer();
    if (!buffer.hasRemaining()) {
        return null;
    }

    byte[] bytes = buffer.array(); // FIXME buffer must has array
    int offset = buffer.arrayOffset() + buffer.position();
    int length = buffer.arrayOffset() + buffer.limit();

    Value v = messagePack.read(bytes, offset, length);
    return v;

    // TODO MessagePack.unpack()
    /*
     * Unpacker pac = new Unpacker(); pac.wrap(bytes, offset, length);
     * return pac.unpackObject();
     */
}
 
Example #14
Source File: Metasploit.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
public Value unpack(byte[] obj) {
    try {
        return MessagePack.unpack(obj);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #15
Source File: RpcMessageHandler.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
private void handleRequest(MessageSendable channel, int msgid,
        String method, Value args) {
    if (server == null) {
        return; // FIXME error result
    }
    server.onRequest(channel, msgid, method, args);
}
 
Example #16
Source File: RpcMessageHandler.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
private void handleResponse(MessageSendable channel, int msgid,
        Value result, Value error) {
    if (session == null) {
        return; // FIXME error?
    }
    session.onResponse(msgid, result, error);
}
 
Example #17
Source File: ReflectionProxyBuilder.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public Object invoke(Object proxy, Method method, Object[] args) {
	ReflectionMethodEntry e = entryMap.get(method);
	if(e == null) {
		// FIXME
	}
	Object[] params = e.sort(args);
	if(e.isAsync()) {
		Future<Value> f = s.callAsyncApply(e.getRpcName(), params);
		return new Future<Object>(messagePack, f, e.getReturnTypeTemplate());
	} else {
		Value obj = s.callApply(e.getRpcName(), params);
		if(obj.isNilValue()){
			return null;
		}else{
			Template tmpl = e.getReturnTypeTemplate();
			if(tmpl == null) {
				return null;
			}
                  try {
                      return tmpl.read(new Converter(messagePack,obj),null);
                      //return messagePack.convert(obj,tmpl);// obj.convert(tmpl);
                  } catch (IOException e1) {
                      return null;
                  }
              }
	}
}
 
Example #18
Source File: ReflectionInvokerBuilder.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public void convert(Object[] params, Value obj) throws MessageTypeException {
    try {
        params[getIndex()] = template.read(new Converter(messagePack,obj),null);//messagePack.convert(obj,template);
    } catch (IOException e) {
        new MessageTypeException(e);
    }
}
 
Example #19
Source File: DecoratorTest.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Test any Exception is not thrown.
 * @throws Exception
 */
@Test
public void testDecorateStopWatch()  throws Exception {

    BasicConfigurator.configure();
    EventLoop loop = EventLoop.start();
    Server svr = new Server(loop);
    svr.setDispatcherBuilder(
            new StopWatchDispatcherBuilder(svr.getDispatcherBuilder()).
                    withVerboseOutput(true)
    );
    Client c = new Client("127.0.0.1", 19850, loop);
    c.setRequestTimeout(10);

    try {
        svr.serve(new TestServer());
        svr.listen(19850);

        Value result = c.callApply("success", new Object[]{});

        assertNotNull(result);

        try{
            c.callApply("throwError", new Object[]{"StopWatchTest"});
            fail("Exception must be thrown.");
        }catch(Exception e){

        }

    } finally {
        svr.close();
        c.close();
        loop.shutdown();
    }
}
 
Example #20
Source File: MsgpackClient.java    From laser with Apache License 2.0 5 votes vote down vote up
public Value read(Object[] req, String method) {
	for (Client client : clients) {
		try {
			return client.callApply(method + "|" + collection, req);
		} catch (Exception e) {
			LOG.debug(e.getMessage());
		}
	}
	return null;
}
 
Example #21
Source File: Metasploit.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
public Map sendList(List list){
    try {
        byte[] result= send(pack(list));
        Value unpack = unpack(result);
        return JSONObject.fromObject(unpack.toString());
    }catch (Exception e){
        SysLog.error(e.getMessage());
    }

    return Collections.EMPTY_MAP;
}
 
Example #22
Source File: MsgpackClient.java    From laser with Apache License 2.0 5 votes vote down vote up
public Object write(Object[] req, String method, Class<?> valueClass)
		throws Exception {
	Value vaule = write(req, method);
	if (null == vaule) {
		return null;
	}
	Converter converter = new org.msgpack.unpacker.Converter(vaule);
	Object ret = converter.read(valueClass);
	converter.close();
	return ret;
}
 
Example #23
Source File: MsgpackByteArrayToMapConverter.java    From spring-integration-zmq with Apache License 2.0 5 votes vote down vote up
public Map<Value, Value> convert(byte[] bytes) {
	
	try {
		return msgpack.read(bytes, template);
	} catch (IOException e) {
		throw new ConversionFailedException(
				TypeDescriptor.valueOf(Map.class), 
				TypeDescriptor.valueOf(byte[].class), 
				bytes, e);
	}
}
 
Example #24
Source File: MsgpackClient.java    From laser with Apache License 2.0 5 votes vote down vote up
public Object asyncRead(Object[] req, String method, Class<?> valueClass)
		throws IOException {
	Value vaule = asyncRead(req, method);
	if (null == vaule) {
		return null;
	}
	Converter converter = new org.msgpack.unpacker.Converter(vaule);
	Object ret = converter.read(valueClass);
	converter.close();
	return ret;
}
 
Example #25
Source File: MessagePackTranscoder.java    From ob1k with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public T decode(final byte[] b) {
  final Template<?> template = messagePack.lookup(valueType);

  try {
    final Value value = messagePack.read(b);
    return (T) template.read(new Converter(messagePack, value), null);
  } catch (final IOException e) {
    throw new SerializationException("Failed to decode to type " + valueType.getTypeName(), e);
  }
}
 
Example #26
Source File: MsgpackParser.java    From transit-java with Apache License 2.0 5 votes vote down vote up
private Object parseLong() throws IOException {
    Value val = mp.readValue();

    try {
        return val.asIntegerValue().getLong();
    }
    catch (Exception ex) {
        BigInteger bi = new BigInteger(val.asRawValue().getString());
    }

    return val;
}
 
Example #27
Source File: TestMessagePack.java    From springJredisCache with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
    public void test() throws IOException {

        // Create serialize objects.
        List<String> src = new ArrayList<String>();
        src.add("msgpack");
        src.add("kumofs");
        src.add("viver");

        MessagePack msgpack = new MessagePack();
// Serialize
        byte[] raw = msgpack.write(src);

// Deserialize directly using a template
        List<String> dst1 = msgpack.read(raw, Templates.tList(Templates.TString));
        System.out.println(dst1.get(0));
        System.out.println(dst1.get(1));
        System.out.println(dst1.get(2));

// Or, Deserialze to Value then convert type.
        Value dynamic = msgpack.read(raw);
        List<String> dst2 = new Converter(dynamic)
                .read(Templates.tList(Templates.TString));
        System.out.println(dst2.get(0));
        System.out.println(dst2.get(1));
        System.out.println(dst2.get(2));
    }
 
Example #28
Source File: ReflectionInvokerBuilder.java    From msgpack-rpc-java with Apache License 2.0 4 votes vote down vote up
public void convert(Object[] params, Value obj) throws MessageTypeException {
	params[getIndex()] = obj.asIntegerValue().getByte();
}
 
Example #29
Source File: DispatcherTest.java    From msgpack-rpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testAsyncHandler2() throws Exception {
    Context context = startServer2(new AsyncHandler());
    Client c = context.getClient();
    try {
        Value result;

        result = c.callApply("m01", new Object[]{});
        assertTrue(result.isRawValue());
        assertEquals("m01", result.asRawValue().getString());

        result = c.callApply("m02", new Object[]{"furuhashi"});
        assertTrue(result.isRawValue());
        assertEquals("m02"+"furuhashi", result.asRawValue().getString());

        result = c.callApply("m03", new Object[]{1978});
        assertTrue(result.isRawValue());
        assertEquals("m03"+1978, result.asRawValue().getString());

        List<String> list = new ArrayList<String>();
        list.add("sadayuki");
        list.add("kumofs");
        result = c.callApply("m04", new Object[]{list});
        assertTrue(result.isRawValue());
        assertEquals("m04"+stringify1(list), result.asRawValue().getString());

        List<List<String>> alist = new ArrayList<List<String>>();
        List<String> alist_n1 = new ArrayList<String>();
        alist_n1.add("1");
        alist_n1.add("2");
        alist_n1.add("3");
        alist.add(alist_n1);
        List<String> alist_n2 = new ArrayList<String>();
        alist_n2.add("a");
        alist_n2.add("b");
        alist_n2.add("c");
        alist.add(alist_n2);
        result = c.callApply("m05", new Object[]{alist});
        assertTrue(result.isRawValue());
        assertEquals("m05"+stringify2(alist), result.asRawValue().getString());

        result = c.callApply("m06", new Object[]{"viver", 2006});
        assertTrue(result.isRawValue());
        assertEquals("m06"+"viver"+2006, result.asRawValue().getString());

    } finally {
        context.close();
    }
}
 
Example #30
Source File: ReflectionInvokerBuilder.java    From msgpack-rpc-java with Apache License 2.0 4 votes vote down vote up
public void convert(Object[] params, Value obj) throws MessageTypeException {
	params[getIndex()] = obj.asIntegerValue().getShort();
}