Kryonet - how to get the sender (Connection) during serialization? - serialization

I have a huge, huge problem. I'm using AES serialization for packets and here comes an issue.
Serializers in Kryo look like this:
public class AESSerializer extends Serializer {
private final Serializer serializer;
public AESSerializer (Serializer serializer) {
this.serializer = serializer;
}
public void write (Kryo kryo, Output output, Object object) {
// USE AES KEY TO ENCRYPT
// WRITE OBJECT
}
public Object read (Kryo kryo, Input input, Class type) {
// USE AES KEY TO DECRYPT
// READ OBJECT
}
}
The problem is here that each user has to have it's own SecretAESKey. I can't find any way to get to the connections lists from the serializer and as I read Kryonet's code - they don't pass it anywhere. I need to get the Connection that writes the object to get it's AES key.
Serializer constructor isn't an option cause serializer is one per application, not for each user.
Do you guys have any idea how to handle things like that?

Kryo has built in this code:
public synchronized void write (Connection connection, ByteBuffer buffer, Object object) {
output.setBuffer(buffer);
kryo.getContext().put("connection", connection);
kryo.writeClassAndObject(output, object);
output.flush();
}
public synchronized Object read (Connection connection, ByteBuffer buffer) {
input.setBuffer(buffer);
kryo.getContext().put("connection", connection);
return kryo.readClassAndObject(input);
}
In your serializer call:
Connection connection = (Connection) kryo.getContext().get("connection");
And you have your connection.

Related

Golang embedding interfaces in struct with private access

I want to replicate the following Java code in Golang in the most idiomatic way possible:
public class Handler {
private Storage storage;
private Mapper mapper;
public Handler(Storage storage, Mapper mapper) {
this.storage = storage;
this.mapper = mapper;
}
public void handleKey(String k) {
storage.put(k, mapper.map(k));
}
}
interface Storage {
public void put(String k, String v);
public String get(String k);
}
#FunctionalInterface
interface Mapper {
public String map(String a);
}
private static class InMemoryStorage implements Storage {
private Map<String, String> table;
public InMemoryStorage() {
table = new HashMap<>();
}
public void put(String k, String v) {
table.put(k, v);
}
public String get(String k) {
return table.get(k);
}
}
Handler class only exposes the method handleKey. The behaviour of this class is parametrized by passing different concrete Storage and Mapper implementations.
After reading Effective Go - Embedding, I thought this would be a good use of embedding interfaces intro structs. But I can't figure out how to avoid exposing the embedded interfaces' methods to Handler users. I can do something like
type Handler struct {
store Storage
mapper Mapper
}
func (h Handler) Handle(k string) {
h.store.Put(k, h.mapper.Map(k))
}
type Storage interface {
Put(k string, v string)
Get(k string) string
}
type Mapper interface {
Map(k string) string
}
type inMemoryStorage {
table map[string]string
}
func NewInMemoryStorage() Storage {
return &inMemoryStore{table: make(map[string]string)}
}
but then I cannot pass concrete implementations to the Handler (creating struct literal) because store and mapper are unexported. And I do not want to create factory methods for each possible combination... Any suggestions?
Those are not embedded; embedding has a specific meaning in Go, as outlined in the spec, and as explained in the Effective Go section you linked to. It refers to unnamed fields, whose fields and methods are accessible implicitly from their containing type. Your fields are named, not embedded.
That said, your two struct fields, store and mapper, are not exported, so they will not be exposed to any user outside the package in which Handler is defined; you seem to already have your desired behavior in that regard.
I'm not sure what you mean when you say you would have to "create factory methods for each possible combination" - I don't see any reason that would be necessary. You need only one factory method:
func NewHandler(s Storage, m Mapper) Handler {
return Handler{store: s, mapper: m}
}
Which could be used with any combination of implementations of Storage and Mapper by passing appropriate values to the function.

Connection String retrieved from one DB to be used in a Class Library to access a 2nd DB...Suggestions?

Environment:
.Net, SQL Server, WinForms Desktop
Control Database (db1)
Customer Databases (db2, db3, db4, etc.)
Background:
Each of our customers requires their own database. It's a contractual obligation due to compliance with standards in certain industries. Certain users of our application only have access to specific databases.
Scenario:
The application user's username gets passed into our control database (db1) from the app on load. There's a lookup in there that determines what customer this user has access to and returns connection string info for connecting to the database of the determined customer (db2 or db3 or db4 or etc.) to be used for the life of the runtime. All of my business logic is in a DAL, as it should be, in a .Net class library.
Suggestions on the best way/ways to get the connection string information into the DAL WITHOUT passing into every constructor/method that is called on the DAL.
I came up with one possible solution, but want to pick your brains to see if there's another or better way.
Possible Solutions:
A Global module in the DAL that has public fields like "dbServer" and "dbName".
Set those and then use the DAL as needed. They would need to be set each time the DAL is used throughout the application, but at least I don't have to make the signature of every single constructor and method require connection string information.
A settings file (preferably XML) that the app writes to after getting the connection info and the DAL reads from for the life of the runtime.
Thoughts and/or suggestions? Thanks in advance.
A set up like this might help. If you are going the IoC way, then you can remove the parameterized constructor and make Connection object a dependency too. However, you will need to feed your dependency injection provider in code since connection string comes from database.
public class User
{
public string ConnectionString
{
get; set;
}
}
public class SomeBusinessEntity
{
}
public class CallerClass
{
public IBaseDataAccess<SomeBusinessEntity> DataAccess
{
get;
set;
}
public void DoSomethingWithDatabase(User user)// Or any other way to access current user
{
// Either have specific data access initialized
SpecificDataAccess<SomeBusinessEntity> specificDataAccess = new SpecificDataAccess<SomeBusinessEntity>(user.ConnectionString);
// continue
// have dependency injection here as well. Your IoC configuration must ensure that it does not kick in until we get user object
DataAccess.SomeMethod();
}
}
public interface IBaseDataAccess<T>
{
IDbConnection Connection
{
get;
}
void SomeMethod();
// Other common stuff
}
public abstract class BaseDataAccess<T> : IBaseDataAccess<T>
{
private string _connectionString;
public BaseDataAccess(string connectionString)
{
_connectionString = connectionString;
}
public virtual IDbConnection Connection
{
get
{
return new SqlConnection(_connectionString);
}
}
public abstract void SomeMethod();
// Other common stuff
}
public class SpecificDataAccess<T> : BaseDataAccess<T>
{
public SpecificDataAccess(string connectionString) : base(connectionString)
{
}
public override void SomeMethod()
{
throw new NotImplementedException();
}
public void SomeSpecificMethod()
{
using (Connection)
{
// Do something here
}
}
}
Create a ConnectionStringProvider class that will provide you the connection string
public class ConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider
// uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Using ConnectionStringProvider in your DAL
public class MyCustomerDAL
{
private ConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
_connectionStringProvider = new ConnectionStringProvider();
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
Setting/changing the connection string
new ConnectionStringProvider()
.SetCustomerConnectionString(connString);
Note
The reason i chose to use method instead of a get/set property in ConnectionStringProvider is because maybe in the future you decide to read/write these from a file, and while you could read/write from file in a property it's misleading to your consumer who thinks that a property will be a simple performance-less hit.
Using a function tells your consumer there might be some performance hit here, so use it wisely.
A little abstration for unit testing
Here is a slight variation that will enable you to abstract for unit testing (and eventually IoC)
public class MyCustomerDAL
{
private IConnectionStringProvider _connectionStringProvider;
public MyCustomerDAL()
{
//since not using IoC, here you have to explicitly new it up
_connectionStringProvider = new ConnectionStringProvider();
}
//i know you don't want constructor, i included this to demonstrate how you'd override for writing tests
public MyCustomerDAL(IConnectionStringProvider connectionStringProvider)
{
_connectionStringProvider = connectionStringProvider;
}
public void UpdateSomeData(object data)
{
using (var con = new SqlConnection(
connectionString: _connectionStringProvider.GetCustomerConnectionString()))
{
//do something awesome with the connection and data
}
}
}
// this interface lives either in a separate abstraction/contracts library
// or it could live inside of you DAL library
public interface IConnectionStringProvider
{
string GetCustomerConnectionString();
void SetCustomerConnectionString(string connectionString);
}
public class ConnectionStringProvider : IConnectionStringProvider
{
// store it statically so that every instance of connectionstringprovider uses the same value
private static string _customerConnectionString;
public string GetCustomerConnectionString()
{
return _customerConnectionString;
}
public void SetCustomerConnectionString(string connectionString)
{
_customerConnectionString = connectionString;
}
}
Appendix A - Using IoC and DI
Disclaimer: the goal of this next piece about IoC is not to say one way is right or wrong, it's merely to bring up the idea as another way to approach solving the problem.
For this particular situation Dependency Injection would make your solving the problem super simple; specifically if you were using an IoC container combined with constructor injection.
I don't mean it would make the code more simple, that would be more or less the same, it would make the mental side of "how do I easily get some service into every DAL class?" an easy answer; inject it.
I know you said you don't want to change the constructor. That's cool, you don't want to change it because it is a pain to change all the places of instantiation.
However, if everything were being created by IoC, you would not care about adding to constructors because you would never invoke them directly.
Then, you could add services like your new IConnectionStringProvider right to the constructor and be done with it.

Replace Conditional with Polymorphism — how it works?

Often i heard that "try to avoid if/switch constructions. If you have them then refactor them to subclasses"
I don't realize how this thing works.
Ok, you have a if/switch in your code. And you create several new classes. But to decide which class you will use you need to implement switch if in fabric class (where you generate these objects). Am i wrong?
P.S. Sorry for my English. I'm reader, not writer.
But to decide which class you will use you need to implement switch if
in fabric class (where you generate these objects). Am i wrong?
No, you are not wrong. While the Polymorphism over switches is a good thing, there are exceptions. One such exception is when you have parameterized factory, and that's absolutely acceptable. So instead of your client code creating specialized classes based on conditions, you will ask such factory to create them for you. Advantage is Factory will solely be responsible for creating those class instances, and if new class is introduced only factory will be modified not client code.
So instead of this:
public class Client {
public string Serialize<T>(string contentType, T instance) where T : class {
switch(contentType) {
case "XML":
return new XMLSerializer().Serialize(instance);
case "JSON":
return new JSONSerializer().Serialize(instance);
}
}
}
You will have this:
public interface ISerializer {
string Serialize(object instance);
object Deserialize(string content);
}
public class XMLSerializer : ISerializer { }
public class JSONSerializer : ISerializer { }
public class SerializerFactory() {
public static ISerializer CreateSerializer(string type) {
switch(type) {
case "XML":
return new XMLSerializer();
case "JSON":
return new JSONSerializer();
}
}
}
public class Client {
public string ParseAPIResponse(string contentType, string responseData) {
ISerializer serializer = SerializerFactory.CreateSerializer(contentType);
var responseObj = serializer.Deserialize(responseData);
}
}
Note there can be only one reason for Factory to change and that is introduction of new Serializer, so we are good on SRP here. Going even further there are ways by which you can avoid modifying factory too, using config files to store identifier-type mappings or simply exposing another method on factory to allow it's users to register new types etc. That's on you.

GWT with Serialization

This is my client side code to get the string "get-image-data" through RPC calls and getting byte[] from the server.
CommandMessage msg = new CommandMessage(itemId, "get-image-data");
cmain.ivClient.execute(msg, new AsyncCallback<ResponseMessage>() {
#Override
public void onFailure(Throwable caught) {
}
#Override
public void onSuccess(ResponseMessage result) {
if (result.result) {
result.data is byte[].
}
}
});
From the server side I got the length of the data is 241336.
But I could not get the value in onSuccess method. It is always goes to onFailure method.
And I got log on Apache:
com.google.gwt.user.client.rpc.SerializationException: Type '[B' was
not included in the set of types which can be serialized by this
SerializationPolicy or its Class object could not be loaded.
How can I do serialisation in GWT?
1) Create a pojo which implements Serializable interface
Let this pojo has all the data you want in the response of RPC service, in this case image-data
2) Pass this pojo in the response for your RPC service.
The below tutorial has enough information for creating RPC service
http://www.gwtproject.org/doc/latest/tutorial/RPC.html
The objects you transfer to and from the server has to implement IsSerializable.
All your custom Objects within the Object you are transferring also needs to implement IsSerializable.
Your objects cannot have final fields and needs an no argument constructor.
You need getters and setters.
A common serialize object in GWT:
public class MyClass implements IsSerializable {
private String txt;
private MyOtherClass myOtherClass; // Also implements IsSerializable
public MyClass() {
}
public String getTxt() {
return this.txt;
}
public void setTxt(String txt) {
return this.txt = txt;
}
public String getMyOtherClass() {
return this.myOtherClass;
}
public void setMyOtherClass(MyOtherClass myOtherClass) {
return this.myOtherClass = myOtherClass;
}
}

ConnectionPoolManager for RedisNativeClient

Is there a Connection Pool Manager available for RedisNativeClient? We are doing byte level operations and use RedisNativeClient instead of the RedisClient.
Here is the solution I implemented. RedisClient inherits RedisNativeClient so using PooledRedisClientManager and then casting the connection to RedisNativeClient works fine. It holds the same TCP socket.
P.S. I am using Dependency Injection so I keep the lifestyle of this helper class singleton.
//Lifestyle is singleton
public class RedisHelper:IRedisHelper
{
private readonly PooledRedisClientManager _poolManager;
public RedisHelper()
{
_poolManager = new PooledRedisClientManager("localhost:6379");
}
public void RedisSingleSet(string redisKey, byte[] redisValues)
{
using (var client = (RedisNativeClient)_poolManager.GetClient())
{
client.Set(redisKey, redisValues);
}
}
}