All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.razorvine.pyro.serializer.SerpentSerializer Maven / Gradle / Ivy

Go to download

This library allows your Java program to interface very easily with the Python world. It uses the Pyro protocol to call methods on remote objects. (See https://pyro5.readthedocs.io/). Pyrolite only implements part of the client side Pyro library, hence its name 'lite'... So if you don't need Pyro's full feature set, Pyrolite may be a good choice to connect java or .NET and python. Version 5.0 changes: support Pyro5 wire protocol. Dropped support of Pyro4 (stick to version 4.xx for that).

There is a newer version: 5.1
Show newest version
package net.razorvine.pyro.serializer;

import java.io.IOException;
import java.util.Map;

import net.razorvine.pyro.Config;
import net.razorvine.pyro.Message;
import net.razorvine.pyro.PyroException;
import net.razorvine.pyro.PyroProxy;
import net.razorvine.pyro.PyroURI;
import net.razorvine.serpent.IDictToInstance;
import net.razorvine.serpent.Parser;
import net.razorvine.serpent.Serializer;
import net.razorvine.serpent.ast.Ast;

public class SerpentSerializer extends PyroSerializer {

	static {
		Serializer.registerClass(PyroURI.class, new PyroUriSerpent());
		Serializer.registerClass(PyroException.class, new PyroExceptionSerpent());
		Serializer.registerClass(PyroProxy.class, new PyroProxySerpent());
	}

	@Override
	public int getSerializerId() {
		return Message.SERIALIZER_SERPENT; 
	}

	@Override
	public byte[] serializeCall(String objectId, String method, Object[] vargs, Map kwargs) throws IOException {
		Serializer s = new Serializer(Config.SERPENT_INDENT, Config.SERPENT_SET_LITERALS, true);
		Object[] invokeparams = new Object[] {objectId, method, vargs, kwargs};
		return s.serialize(invokeparams);
	}

	@Override
	public byte[] serializeData(Object obj) throws IOException {
		Serializer s = new Serializer(Config.SERPENT_INDENT, Config.SERPENT_SET_LITERALS, true);
		return s.serialize(obj);
	}

	@Override
	public Object deserializeData(byte[] data) throws IOException {
		Parser p = new Parser();
		Ast ast = p.parse(data);
		IDictToInstance dictConverter = new DictConverter();
		return ast.getData(dictConverter);
	}
	
	class DictConverter implements IDictToInstance
	{
		public Object convert(Map dict) throws IOException {
			String classname = (String)dict.get("__class__");
			boolean isException = dict.containsKey("__exception__") && (Boolean)dict.get("__exception__");
			if(isException)
			{
				// map all exception types to the PyroException
				return PyroExceptionSerpent.FromSerpentDict(dict);
			}
			if("Pyro4.core.URI".equals(classname))
				return PyroUriSerpent.FromSerpentDict(dict);
			else if("Pyro4.core.Proxy".equals(classname))
				return PyroProxySerpent.FromSerpentDict(dict);
			else
				return null;
		}
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy