Decorators in Hyperledger Composer Modeling Language - decorator

I am quite new to Hyperledger Composer and I really need your help guys!
I need an asset that would be defined dynamically with N amount of properties which aren't known at this moment and would be defined by the end user.
I assume that this could be done by using decorators in the modeling language, but I didn't find any examples that fully explains how to use them including Front-End interaction.
To be more clear I need an advice on how is it possible to implement something like this as a result:
asset $CustomNameFromFrontEnd {
o String id
o $TypeFromFrontEnd1 $PropertyNameFromFrontEnd1
o $TypeFromFrontEnd2 $PropertyNameFromFrontEnd2
…
o $TypeFromFrontEndN $PropertyNameFromFrontEndN
}
I would really appreciate if someone could help me with an example how should I describe the asset in .cto file and how should I implement asset creation in the logic.js file.

I don't think Decorators, documented at the bottom of the Modeling Language topic, do what you want. Decorators are added to the model at design time, just like all the properties. For example, you could add annotations to influence some UI code generation:
#frontEndApp("customArgument")
asset CustomAsset {
o String id
o String customProperty1
}
Depending on how often the shape of the data changes, and what proportion of the data is dynamic, you might be able to try:
generating a model based on input from a front end app (pretty much the yo generator use case)
using a static model for most of the data but using getNativeAPI in your logic for small pieces of data that do not have a model
using Fabric without the Composer tools

I've figured out how to deal with that. Maybe it will be useful to someone else. Here is how I defined CustomAsset:
enum FieldType {
o String
o Double
o Boolean
o Integer
o DateTime
o Long
}
concept customFieldName {
o String customFieldName
}
concept customFieldValue {
o FieldType customFieldValue
}
concept customField {
o customFieldName customFieldName
o customFieldValue customFieldValue
}
asset CustomAsset identified by id {
o String id
o String assetName
o customField[] customFields
}
transaction CreateCustomAsset {
o CustomAsset customAsset
}

Related

Java: Using .stream to transform ArrayList<MyObj> to TreeMap<String, ArrayList<MyObj>>

This is a Java 8 lower-intermediate question:
I have the following code in Java 6:
List <ViewWrapperContentElementTypeProperty> vwPropertyList = getFromDao();
TreeMap <Long, ArrayList<ViewWrapperContentElementTypeProperty>> mappedProperties = new TreeMap<Long, ArrayList<ViewWrapperContentElementTypeProperty>> ();
for (ViewWrapperContentElementTypeProperty vwCetP:vwPropertyList)
{
if(null==mappedProperties.get(vwCetP.getContentElementTypeId()))
{
ArrayList<ViewWrapperContentElementTypeProperty> list = new ArrayList<ViewWrapperContentElementTypeProperty>());
list.add(vwCetP);
mappedProperties.put(vwCetP.getContentElementTypeId(), list);
}
else
{
mappedProperties.get(vwCetP.getContentElementTypeId()).add(vwCetP);
}
}
Can I use vwPropertyList.stream().map() to implement this more efficiently?
It seems like you are looking for a grouping by operation. Fortunately, the Collectors class provide a way to do this:
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toCollection;
...
TreeMap<Long, ArrayList<ViewWrapperContentElementTypeProperty>> mappedProperties =
vwPropertyList.stream()
.collect(groupingBy(ViewWrapperContentElementTypeProperty::getContentElementTypeId,
TreeMap::new,
toCollection(ArrayList::new)));
I used the overloaded version of groupingBy where you can provide a specific map implementation (if you really need a TreeMap).
Also the toList() collector returns a List (which is an ArrayList but it's an implementation details). Since you apparently need to specify a concrete implementation as you want ArrayLists as values, you can do it with toCollection(ArrayList::new).
With regard to using Streams and lambda expressions, of course... This should look like the following:
Map<Long, List<ViewWrapperContentElementTypeProperty>> mappedProperties =
vwPropertyList.stream()
.collect(Collectors.groupingBy(ViewWrapperContentElementTypeProperty::getContentElementTypeId));
Please note that using Stream API methods like above forces using interfaces (Map, List), which is a good practice anyway.
When it comes to performance, it should be roughly the same as using a traditional loop.

LINQ and web service cannot return anonymous types, and you cannot construct an object in a query?

Web services cannot return an anonymous type.
If you are building a LINQ query using classes through a datacontext... you cannot construct instances of those classes in a query.
Why would I want to do this? Say I want to join three "tables" or sets of objects. I have three items with a foreign key to each other. And say the lowest, most detailed of these was represented by a class that had fields from the other two to represent the data from those. In my LINQ query I would want to return a list of the lowest, most detailed class. This is one way I have decided to "join some tables together" and return data from each of them via LINQ to SQL via a WebService. This may be bad practice. I certainly do not like adding the additional properties to the lowest level class.
Consider something like this... (please ignore the naming conventions, they are driven by internal consideration) also for some reason I need to instantiate an anonymous type for the join... I don't know why that is... if I do not do it this way I get an error...
from su in _dataContext.GetTable<StateUpdate>()
join sfs in _dataContext.GetTable<SystemFacetState>()
on new { su.lngSystemFacetState } equals new { lngSystemFacetState = sfs.lngSystemFacetState }
join sf in _dataContext.GetTable<SystemFacet>()
on new { sfs.lngSystemFacet } equals new { lngSystemFacet = sf.lngSystemFacet }
join s in _dataContext.GetTable<System>()
on new { sf.lngSystem } equals new {lngSystem = s.lngSystem}
select new
{
lngStateUpdate = su.lngStateUpdate,
strSystemFacet = sf.strSystemFacet,
strSystemFacetState = sfs.strSystemFacetState,
dtmStateUpdate = su.dtmStateUpdate,
dtmEndTime = su.dtmEndTime,
lngDuration = su.lngDuration,
strSystem = s.strSystem
}
).ToList();
Notice I have to build the anonymous type which is composed of pieces of each type. Then I have to do something like this... (convert it to a known type for transport via the web service)
result = new List<StateUpdate>(from a in qr select(new StateUpdate
{
lngStateUpdate = a.lngStateUpdate,
strSystemFacet = a.strSystemFacet,
strSystemFacetState = a.strSystemFacetState,
dtmStateUpdate = a.dtmStateUpdate,
dtmEndTime = a.dtmEndTime,
lngDuration = a.lngDuration,
strSystem = a.strSystem
}));
It is just awful. And perhaps I have created an awful mess. If I am way way off track here please guide me to the light. I feel I am missing something fundamental here when I am adding all these "unmapped" properties to the StateUpdate class.
I hope someone can see what I am doing here so I can get a better way to do it.
You can create a 'dto' class which just contains the properties you need to return and populate it instead of the anonymous object:
public class Result
{
public string lngStateUpdate
{
get;
set;
}
... // other properties
}
then use it like this:
from su in _dataContext.GetTable<StateUpdate>()
...
select new Result
{
lngStateUpdate = su.lngStateUpdate,
... // other properties
}
Nitpick note - please ditch the Hungarian notation and camel casing for properties :)
I think the answer is to create another object to serve as a DTO. This object would not be mapped to the data context and can contain fields that cross the mapped objects. This solves the problems of repetitive properties in the mapped objects, and allows for instantiation of the DTO class in the query as it is not mapped.
FYI: with respect to the problem with the join- I revisited that and I think I may have had the inner and outer components of the join switched around before.

Understanding the relationship between Liskov and OCP

I am solidifying my understanding of the relationship between Liskov Substitutional Principal and Open Close Principal. If anybody could confirm my deductions and answer my questions below that would be great.
I have the following classes. As you can see, B is derived from A and it is overriding the DisplayMessage function in order to alter the behavior.
public class A
{
private readonly string _message;
public A(string message)
{
_message = message;
}
public virtual void DisplayMessage()
{
Console.WriteLine(_message);
}
}
public class B : A
{
public B(string message) : base(message){}
public override void DisplayMessage()
{
Console.WriteLine("I'm overwriting the expected behavior of A::DisplayMessage() and violating LSP >:-D");
}
}
Now in my bootstrap program, ShowClassTypeis expecting an object of Type A which should helpfully write out what class Type it is. However B is violating LSP so when it's DisplayMessage function is called it prints a completely unexpected message and essentially interferes with the intended purpose of ShowClassType.
class Program
{
static void Main(string[] args)
{
A a = new A("I am A");
B b = new B("I am B");
DoStuff(b);
Console.ReadLine();
}
private static void ShowClassType(A model)
{
Console.WriteLine("What Class are you??");
model.DisplayMessage();
}
}
So my question is, am I right to conclude that ShowClassType is now violating the Open Close Principal because now that Type B can come in and change the expected function of that method, it is no longer closed for modification (ie. to ensure it maintains it's expected behaviour you would have to alter it so that it first checks to make sure we are only working with an original A object)?
Or, inversely is this just a good example to show that ShowClassType is closed for modification and that by passing in a derived type (albeit a LSP violating one) we have extended what it is meant to do?
Lastly, is it bad practice to create virtual functions on Base classes if the base class is not abstract? By doing so, are we not just inviting derived classes to violate the Liskov Substitution principal?
Cheers
I'd say it's not ShowClassType that is violating the Open/Closed Principle.
It's only class B that is violating the Liskov Substitution Principle. A is Open for extension, but closed for modification.
From Wikipedia,
an entity can allow its behaviour to be modified without altering its source code.
It's obvious that the source code of A is not modified. Nor are private members of A being used (which would also be a violation of the Open/Closed principle in my book). B strictly uses the public interface of A, so although the Open/Closed principle is obeyed the Liskov Substitution Principle is violated.
The last question is worth a discussion in and of itself. A related question on SO is here.
I think it is not violate not LSP and not OCP in THIS context of using.
For my opinion, ShowClassType not violation OCP:
1. Function can not break OCP, only class architecture can do this.
2. You can add new behaviours to derived classes from A - so it do not break OCP
What about LSP? Your reason - user not expected get this message? But he got some message! If function overriding returns some message i think is ok in THIS context of your code.
If function, that add two numbers is overrides, and 1+1 returns 678 it not expectable for me and is bad. BUT, if for scientist of Physics from Mars planet it can be good answer.
DO NOT ANALYSE PROBLEM WITHOUT ALL CONTEXT!!! You must get whole picture of problem. And, of course

Grails data binding

A Grails controller received is called with the following request parameters:
defaultPrice[0].amount 22
defaultPrice[0].currency 1
defaultPrice[0].id
defaultPrice[1].amount 33
defaultPrice[1].currency 3
defaultPrice[1].id
I've defined the following command class:
class PriceCommand {
BigDecimal amount
Integer currency
Integer id
}
I attempt to bind the request parameters to a `List' in the action
def save = {List<PriceCommand> defaultPrice ->
}
But within the action, defaultPrice is null.
It requires an command with existing list of data, with specified name, that will be filled with data from request.
Try
import org.apache.commons.collections.ListUtils
import org.apache.commons.collections.Factory
class PriceListCommand {
List<PriceCommand> defaultPrice = ListUtils.lazyList([], {new PriceCommand()} as Factory)
}
and use this command inside controller. It should works
I'm not sure if this is what your looking but it may help...
1.) I think indexed params only work if you have a parent-child or one-to-many relationship. For example you might need to introduce a PriceCommandParent which contains a list of PriceCommand. I may be wrong on this and I welcome any corrections.
2.) I've found that indexed params aren't as magically as some of the other areas of Grails/Groovy so sometimes i'd rather deal with the mapping myself. Below is how i've handled it in the past....
def things = []
params.each{name, value->
if (name.matches('^(thing\\[\\d+\\])$')){ //<-- look for 'thing[x]'
things.add(new Thing(params[name]);
}
}
Let me know if any of this is of help

different hashtable cacheItem with similar data values or separate cacheItems for each data value – which is an efficient approach?

I have broadly two different classes of data caching requirements based on data size:
1) very small data (2-30 characters) – this includes such things as the type code for a given entityId. The system is based upon the concept of parent-child entity hierarchy and actions are authorized against values that are built in combination with entity type code. Caching these type codes for different entities saves time on db fetch.
2) medium/Large data – This is general data like products description and pages.
I'm confused as to which approach is better suited for first class of data.
I can cache it like this:
HttpRuntime.Cache.Insert("typeCode" + entityId, entityTypeCode);
or like this:
Dictionary<int, string> etCodes =
(Dictionary<int, string>)HttpRuntime.Cache["typeCode"];
etCodes[entityId] = entityTypeCode;
Clearly, In the second approach, I'm saving on unnecessary cache items for each entityId.
or, having Cache object populated with several items of such small size is okay.
Which of these approachs is good in terms of performance and overhead?
Personally I would take your second approach of one single object and use a custom object instead of a Dictionary.
This would enable me to later control more aspects like expiration of items within the object or changing the implementation.
I would do it similar to this:
public class MyCacheObject
{
public static MyCacheObject
{
get
{
// ...Omitted locking here for simplification...
var o = HttpRuntime.Cache["MyCacheObject] as MyCacheObject;
if ( o = null )
{
o = new MyCacheObject();
HttpRuntime.Cache["MyCacheObject] = o;
}
return o;
}
}
public object GetEntity( string id, string code )
{
// ...
}
public void SetEntity( object entity, string id, string code )
{
// ...
}
// ...
}
If you have a custome base class for the entities, the GetEntity and SetEntity methods could be optimized further.

Resources