using in-memory data-structures - in-memory-database

I have a client requirement of
not to use an RDBMS, but instead do everything using in-memory data-structures If the server is restarted then the application state will revert to the last state saved.
I don't have any idea of using in-memory data , I used to work with MySQL ,but not in memory
If anyone could please guide me a bit about this , any tutorial or something
Below are some examples ...
public Object save(Object object, Class c) {
database.ofy().put(object);
return object;
}
public void delete(Long id, Class c) {
database.ofy().delete(c, id);
}
public Object findById(String id, Class c) {
return database.ofy().find(c, id);
}
public Iterable<Object> findAll(Class c) {
Iterable<Object> models = database.ofy().query(c).fetch();
return models;
}
}
Thanks

you can use sqlite, which has hooks to a lot of languages.
the default use for sqlite is for file-based, but it can easily be used in-memory.

Related

Java CXF: What is the best way to handle Common Objects under different packages or namespaces?

We're integrating with a 3rd Party webservice by using Wsdl2Java to translate their Schema and endpoints into Java for three different webservices that they offer.
This particular provider uses a lot of the same objects (think objects representing an Address, Money, Weight, etc), but, in their infinite wisdom, they've decided to create a different namespace for each webservice and duplicate the definition of their schemas for each one. The result is you have the following classes output for CXF integration:
com.thirdpartyguys.api.firstApi.Money
com.thirdpartyguys.api.secondApi.Money
com.thirdpartyguys.api.thirdApi.Money
Translating our data into theirs can involve a lot of business logic and, as a result, we have to define the code that creates the objects in triplicate for each individual Webservice API.
To overcome this problem I created an Interface defined thusly:
import org.apache.commons.beanutils.BeanUtils;
public interface CommonObjectInterface<A, R, S> {
A toFirstApi();
R toSecondApi();
S toThirdApi();
default Object doTransform(Object destination, Object source) {
try {
BeanUtils.copyProperties(destination, source);
} catch (Exception e) {
throw new RuntimeException("Fatal error transforming Object", e);
}
return destination;
}
}
You would then have each common object implement the interface, define its own constructors, fluent API, etc, and call the toXXX() methods to get the proper form of the object for the respective API.
Right now most of these implementing classes work by keeping a copy of one of the Apis locally, setting data on that, and then transforming it for the proper API using the doTransform() method which in its default form uses the Apache Commons BeanUtils.copyProperties() method.
It's more elegant than having the same code exist in three different places, but not by much! There's a lot of boilerplate and, even though this won't be getting hammered too much, not that efficient.
I would like to get feedback from the community as to whether this is a good idea or if there are better approaches. A similar question was asked years ago here, but I don't know if better solutions have emerged since it was asked. I imagine the best thing would be configuring wsdl2Java to allow setting the namespace at runtime, but from my initial research this does not seem to be possible.
The solution to this problem is specific to this exact situation:
1) A webservice provider that has the same object in different namespaces
2) Using wsdl2Java or some underlying Apache CXF technology to generate the web artifacts for writing a client.
This is a fringe case so I'm not sure how helpful this will be to the community but the trick is to account for a few situations where a copyProperties method doesn't work. In this case I'm using Spring's BeanUtils and BeanWrapper classes although I'm sure this could be adapted for Apache as well. The following code does the trick:
final String TARGET_PACKAGE = "com.thirdpartyguys.api";
public Object doTransform(Object destination, Object source) {
/*
* This will copy all properties for the same data type for which there is a getter method in
* source, and a setter method in destination
*/
BeanUtils.copyProperties(source, destination);
BeanWrapper sourceWrapper = new BeanWrapperImpl(source);
for(PropertyDescriptor p : sourceWrapper.getPropertyDescriptors()) {
/*
* Properties that are references to other schema objects are identical in structure, but have
* different packages. We need to copy these separately
*/
if(p.getPropertyType().getPackage().getName().startsWith(TARGET_PACKAGE)) {
try {
commonPropertyCopy(destination, source, p);
} catch (Exception e) {
throw new RuntimeException("Fatal error creating Data", e);
}
}
/*
* Properties that reference list don't create setters according to the Apache CXF
* convention. We have to call the get method and addAll()
*/
else if(Collection.class.isAssignableFrom(p.getPropertyType())) {
try {
collectionCopy(destination, source, p);
} catch (Exception e) {
throw new RuntimeException("Fatal error creating Data", e);
}
}
}
return destination;
}
private void collectionCopy(Object destination, Object source, PropertyDescriptor sourceProperty) throws Exception {
BeanWrapper destWrapper= new BeanWrapperImpl(destination);
PropertyDescriptor destProperty = destWrapper.getPropertyDescriptor(sourceProperty.getName());
Collection<?> sourceCollection = (Collection<?>) sourceProperty.getReadMethod().invoke(source);
Collection<Object> destCollection = (Collection<Object>) destProperty.getReadMethod().invoke(destination);
destCollection.addAll(sourceCollection);
}
private void commonPropertyCopy(Object destination, Object source, PropertyDescriptor sourceProperty) throws Exception {
if(sourceProperty.getPropertyType().isEnum()) {
instantiateEnum(destination, source, sourceProperty);
}
else {
instantiateObject(destination, source, sourceProperty);
}
}
private void instantiateEnum(Object destination, Object source, PropertyDescriptor sourceProperty) throws Exception {
BeanWrapper destWrapper= new BeanWrapperImpl(destination);
Enum<?> sourceEnum = (Enum<?>) sourceProperty.getReadMethod().invoke(source);
PropertyDescriptor destProperty = destWrapper.getPropertyDescriptor(sourceProperty.getName());
Object enumValue = Enum.valueOf(destProperty.getPropertyType().asSubclass(Enum.class), sourceEnum.name());
destProperty.getWriteMethod().invoke(destination, enumValue);
}
private void instantiateObject(Object destination, Object source, PropertyDescriptor sourceProperty) throws Exception {
Object subObj = sourceProperty.getReadMethod().invoke(source);
if(subObj!=null) {
BeanWrapper destWrapper = new BeanWrapperImpl(destination);
String subObjName = sourceProperty.getName();
PropertyDescriptor destProperty = destWrapper.getPropertyDescriptor(subObjName);
Class<?> propertyType = destProperty.getReadMethod().getReturnType();
Object subObjCopy = propertyType.getConstructor().newInstance();
doTransform(subObjCopy, subObj);
destProperty.getWriteMethod().invoke(destination, subObjCopy);
}
}
instantiateObject is used to create new instances of the "identical" objects from different packages. This also applies for Enumerated types and requires its own method, hence the implementation of instantiateEnum. Finally, the default CXF implemenation offers no setter method for Lists. We handle this situation in collectionCopy.

OOP: Proper way to check other instances of objects' variables

I have a collection of related classes, call them
class Manager {
private:
std::vector<Setting> m_settings;
}
class Setting {
private:
std::vector<Action> m_actions;
}
class Action {
private:
Keybind m_keybind;
}
class Keybind {
public:
UpdateKeybind;
private:
TYPE keybind;
}
As you can see from the pseudo-C++ code, Settings have actions, and actions have exactly one key binding. Now, as a user of my application you want to update the Keybind potentially, yes?
I currently have buttons in a keybind-type dialog associated with each action, so the action can handle updating it's own keybind.
My Problem:
How do I ensure that the Keybinding isn't bound to another object?
Possible solutions:
Move UpdateKeybind itself to the Manager class, then have Manager query all the settings.
Have a parent pointer in Action/Setting/Keybind so the Action can query the manager for updated keybind.
Have the Action query other Actions (not great conceptually as far as I can tell).
What I need from you:
What is the most rigorous approach, in terms of maintainability, speed, ease of understanding, and OOP appropriateness, to implementing checking if a Keybind is already found, whether out of my suggested solutions or something else entirely. I have already tried number 1 -- it works, but I feel like it could be better, ya dig?
I was unable to find similar questions on StackOverflow, but if you do I'd love to see them!
Any other pro tips, things to improve are helpful.
Just like #Amardeep says, you can try creating a class managing the mapping between actions and keybindings. Following is an example. It will automatically remove the keybind to the action if the there is new binding to that keybind.
class Manager {
private:
std::vector<Setting*> m_settings;
KeybindPool *m_keybindPool;
};
class Setting {
private:
std::vector<Action*> m_actions;
};
class Action {
public:
void Bind(Keybind* keybind) {
m_manager->m_keybindPool->Update(this, keybind)
}
Keybind* getKeybind() const {
return m_manager->m_keybindPool->getKeybind(this);
}
private:
Manager *m_manager;
};
class KeybindPool {
public:
void Update(Action* action, Keybind* keybind) {
if (m_keybindActionMap.find(keybind) != m_keybindActionMap.end()) {
m_actionKeybindMap.erase(action);
}
m_keybindActionMap[keybind] = action;
m_actionKeybindMap[action] = keybind;
}
Keybind* getKeybind(Action* action) {
return m_actionKeybindMap[action];
}
private:
map<Keybind*, Action*> m_keybindActionMap;
map<Action*, Keybind*> m_actionKeybindMap;
};
class Keybind {
private:
TYPE keybind;
}
Since you have an exactly 1:1 relationship between key bindings and actions, you could start with a pool of key binding objects and draw down from the pool as you configure actions. So when offering up available keys for configuration, any keys already bound would not be in the available pool.

Create System.Data.Linq.Table in Code for Testing

I have an adapter class for Linq-to-Sql:
public interface IAdapter : IDisposable
{
Table<Data.User> Activities { get; }
}
Data.User is an object defined by Linq-to-Sql pointing to the User table in persistence.
The implementation for this is as follows:
public class Adapter : IAdapter
{
private readonly SecretDataContext _context = new SecretDataContext();
public void Dispose()
{
_context.Dispose();
}
public Table<Data.User> Users
{
get { return _context.Users; }
}
}
This makes mocking the persistence layer easy in unit testing, as I can just return whatever collection of data I want for Users (Rhino.Mocks):
Expect.Call(_adapter.Users).Return(users);
The problem is that I cannot create the object 'users' since the constructors are not accessible and the class Table is sealed. One option I tried is to just make IAdapter return IEnumerable or IQueryable, but the problem there is that I then do not have access to the methods ITable provides (e.g. InsertOnSubmit()). Is there a way I can create the fake Table in the unit test scenario so that I may be a happy TDD developer?
My current solution is to wrap the functionality I want from Table into a TableWrapper class:
public interface ITableWrapper<TEntity>
where TEntity : class
{
IEnumerable<TEntity> Collection { get; }
void InsertOnSubmit(TEntity entity);
}
And here's the implementation:
public class TableWrapper<TEntity> : ITableWrapper<TEntity>
where TEntity : class
{
private readonly Table<TEntity> _table;
public TableWrapper(Table<TEntity> table)
{
_table = table;
}
public IEnumerable<TEntity> Collection
{
get { return _table; }
}
public void InsertOnSubmit(TEntity entity)
{
_table.InsertOnSubmit(entity);
}
}
So now I can easily mock data from Collection, as well as keeping the functionality of InsertOnSubmit (any other functions that I need down the road can be added later on).
I have had success using the Data Access Layer to produce domain object collections and then using linq to objects.
The object under test then only relates to List, which is fairly easy to unit test.
I don't like when the logic entities should have Data Access Layer dependencies. They should stop at the service layer, if even there. I usually go for the model where the service layer invokes a data access object to get a List, passes that list into whichever logic object that needs it (if necessary uses linq-to-objects to filter out the relevant data and injects it into eiter a flat list, dictionary or an object model).
The business objects become very testable, even though they don't benefit from the richness of the inferred data model.

testing entity mapping of NHibernate

i'm building some basic crud methods for my fluently mapped entities.
i just wanna know if there is a simple way to make the transaction to perform a rollback when i'm running the cud test methods ?
the code that being tested perform the commit inside
here is a create sample:
public int? Create(IIdentifiable entity)
{
int? newId = null;
using (ISession session = SessionFactoryProvider.NewSession)
using (ITransaction transaction = session.BeginTransaction())
{
object newObj = session.Save(entity);
newId = (int?)newObj;
transaction.Commit();
}
return (int?)newId;
}
If you're using xUnit.net, there's an AutoRollback attribute in the contrib project. If you're open to using System.Transactions then you can create a new transaction before the session.Open() and session should autoenlist (unless you've set ado.net to not autoenlist). Then just abandon at the end.
I did something similar to this a (long) while ago:
public class TransactionalTest
{
public TransactionalTest()
{
Transaction.Current = new CommittableTransaction();
}
~TransactionalTest()
{
if (Transaction.Current != null &&
Transaction.Current.TransactionInformation.Status !=
TransactionStatus.Committed)
{
Transaction.Current.Rollback();
}
}
}
Then just have your test extend TransactionalTest. But, I think NUnit, MbUnit and xUnit.net all support transactional tests out of the box or with a contrib project.
Check FUBUMVC Contrib for a great NHibernate CRUD testing method.
Hmm, I don't think that it is a good idea to let your method create a session and perform transaction handling .... Unless that method is also a service boundary.
Suppose you want to create multiple entities in one and the same transaction, how are you going to handle that ?
For integration testing, I use a session decorator to auto commit and evict the entity. You could adapt it for your situation:
public class AutoCommitAndEvictSession : SessionDecorator {
public AutoCommitAndEvictSession(ISession session)
: base(session) { }
public override object Save(object obj) {
object result;
using (var tx = Session.BeginTransaction()) {
result = Session.Save(obj);
tx.Commit();
}
Session.Evict(obj);
return result;
}
public override void Update(object obj) {
CommitAndEvict(base.Update, obj);
}
public override void Delete(object obj) {
CommitAndEvict(base.Delete, obj);
}
private void CommitAndEvict(Action<object> action, object entity) {
using (var tx = Session.BeginTransaction()) {
action.Invoke(entity);
tx.Commit();
}
Session.Evict(entity);
}
}
You can find more details on usage with examples here:
http://www.agileatwork.com/integration-testing-with-nhibernate/

Alternative of using built-in object that implements IDictionary for a web method

I have a web application that uses the Web Service created in ASP.NET. In this, web service I want to pass an collection object of Key Value type (i.e. something like Hashtable or Dictionay).
But we cannot use objects that implements from IDictionary.
I do not want to create a serialized class in my web service.
Can anyone suggest me the best approach for this?
dev.e.loper is almost right. You can use a List<Pair>.
Alternatively, you can use List<KeyValuePair<TKey,TValue>>.
MSDN Documentation:
KeyValuePair
Pair
I'm not totally clear on your question, but maybe you are needing something like this?
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
var keySerializer = new XmlSerializer(typeof(TKey));
var valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement("item");
reader.ReadStartElement("key");
var key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement("value");
var value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
public void WriteXml(XmlWriter writer)
{
var keySerializer = new XmlSerializer(typeof(TKey));
var valueSerializer = new XmlSerializer(typeof(TValue));
foreach (var key in this.Keys)
{
writer.WriteStartElement("item");
writer.WriteStartElement("key");
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement("value");
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
You can inherit from KeyedCollection which is Serializable.
http://msdn.microsoft.com/en-us/library/ms132438.aspx
I solved this by using DictionaryEntry
The only difference is that Key is Object as well.
I basically have a Dictionary ToDictionary(DictionaryEntry[] entries) and a DictionaryEntry[] FromDictionary(Dictionary entries) static methods which are very light weight and end up getting me to the same place without having to make my own collection class.
The added benefit is that the XML which comes as a result is closer to that in which the WCF Web Services use by default! That means you can make this change now in your client code and be ready for WCF if you decide to move that way.
The result looks like this over JSON [{"Key": key1, "Value": value1}, {"Key": key2, "Value": value2}] exactly the same as it does over WCF by default.
You could try to use 2 arrays, 1 for keys and one for values, where the indexes of the arrays match up. Not the most ideal solution but a valid one. The internals of the webservice you can use IDictionary and just pass out the Keys and Values of that object.