Intercepting Method Access on the Host Program of IronPython - scripting

Greetings,
Most of the information I see around concerning the construction of Proxies for objects assume that there exists a Type somewhere which defines the members to be proxied. My problem is: I can't have any such type.
To make the problem simpler, what I have is a dictionary that maps strings to objects. I also have getters and setters to deal with this dictionary.
My goal then is to provide transparent access inside IronPython to this getters and setters as if they were real properties of a class. For example, the following code in a python script:
x.result = x.input * x.percentage;
...would actually represent something like in the host language:
x.SetProperty("result", x.GetProperty("input") * x.GetProperty("percentage"));
Also, 'x' here is given by the host program. Any ideas? Please remember that I cannot afford the creation of a typed stub... Ideally, I would be happy if somehow I could intercept every call to an attribute/method of a specific object in the script language onto the host program.

This post might be useful.

Related

From a ByteBuddy-generated method, how do I set a (public) instance field in an object received as an argument to the return value of a MethodCall?

I am generating a class in ByteBuddy.
As part of one method implementation, I would like to set a (let's just say) public instance field in another object to the return value of a MethodCall invocation. (Keeping the example public means that access checks etc. are irrelevant.)
I thought I could use MethodCall#setsField(FieldDescription) to do this.
But from my prior question related to this I learned that MethodCall#setsField(FieldDescription) is intended to work only on fields of the instrumented type, and, looking at it now, I'm not entirely sure why or how I thought it was ever going to work.
So: is there a way for a ByteBuddy-generated method implementation to set an instance field of another object to the return value of a method invocation?
If it matters, the "instrumented method" (in ByteBuddy's terminology) accepts the object whose field I want to set as an argument. Naïvely I'd expect to be able to do something like:
MethodCall.invoke(someMethod).setsField(somePublicField).onArgument(2);
There may be problems here that I am not seeing but I was slightly surprised not to see this DSL option. (It may not exist for perfectly good reasons; I just don't know what they would be.)
This is not possible as of Byte Buddy 1.10.18, the mechanism was originally created to support getters/setters when defining beans, for example. That said, it would not be difficult to add; I think it would even be easiest to allow any custom byte code to be dispatched as a consumer of the method call.
I will look into how this can be done, but as a new feature, this will take some time before I find the empty space to do so. The change is tracked on GitHub.

How to dynamically create fb instances during runtime on a plc?

I'm new to PLC programming and we need to create a library for a project. We need dynamically created function block instances during the runtime. There is a concept described on the codesys homepage:
https://help.codesys.com/webapp/fb_factory;product=LibDevSummary;version=3.5.15.0
We tried to implement the example but without success. Unfortunately, there is no further information about the concept on the codesys homepage.
Has anybody some advice how to dynamically create fb instances during the runtime on a plc?
When you want to create an instance of an FB dynamically you need first to put the following attribute above the FB-Declaration:
{attribute 'enable_dynamic_creation'}
Then you must make sure you are not calling __NEW(FB_NAME) cyclically.
Then you assign the result of __NEW(FB_NAME) to a pointer:
//Put this is the declaration section
pfbName : POINTER TO FB_NAME;
//Your call to create a dynamic instance
pfbName := __NEW(FB_NAME);
If your pointer = 0 after __NEW returns, it means __NEW failed to allocate memory.
I made a simple classic OOP Person, Teacher, Student example here.
Basically, changing the value of numberOfTeachers inside PLC_PRG will cause the reinitializarion of the array people with the first numberOfTeachers entries being Teachers, and the rest being Students. You can look at the Device Logs where I write messages for creation/destruction of Teacher/Studemt.
PS. I am myself still exploring the possibilities of the Factory Design in CODESYS, so excuse me if I made any mistakes!

Endeca Assembler: Customize response header

I want to insert a new (key -> value) pair in response header from Endeca Assembler. Is it possible to do this?
Thanks
First of all, I want to clarify some things because the terminology about Assembler can get a little confusing. I'm not sure how you have designed your program, but just keep in mind that Assembler is just a Java API, so it's kind of unclear to say something like "response header from Endeca Assembler". That statement seems to imply that Assembler is a webservice, but it isn't. In my experience, people commonly mistakenly refer to the discover-data (Discover service) example app as "Assembler" or "Assembler Service", but it really isn't a general-purpose webservice; it's designed as a reference application to be used specifically with the Discover dataset (But people still use discover-data as a starting point for building production-facing applications). So, bear in mind that I'm not exactly sure what you are referring to.
Anyway, somewhere in your code, you should have a call of something like "contentItem.assemble()", which runs your cartridge handlers on that content item and returns an object of type ContentItem. In the Discover webapp, it then serializes this content item to JSON or XML or renders a JSP page (depending on the request parameters). I assume your application does something similar.
It's a simple matter of adding properties to ContentItem, because ContentItem implements map. So, you can do something like this:
ContentItem responseContentItem = contentItem.assemble();
responseContentItem.put("myKey","myValue");
...continue by serializing responseContentItem or whatever you want to do with it
Do like this:
responseContentItem.put("key", "value");
as the resposne from Endeca Assembler is simply a Map.

Creating an Objective-C API

I have never made an API in objective-c, and need to do this now.
The "idea" is that I build an API which can be implemented into other applications. Much like Flurry, only for other purposes.
When starting the API, an username, password and mode should be entered. The mode should either be LIVE or BETA (I guess this should be an NSString(?)), then afterwards is should be fine with [MyAPI doSomething:withThisObject]; ect.
So to start it [MyAPI username:#"Username" password:#"Password" mode:#"BETA"];
Can anyone help me out with some tutorials and pointer on how to learn this best?
It sounds like what you want to do is build a static library. This is a compiled .a file containing object code that you'll distribute to a client along with a header file containing the interface. This post is a little outdated but has some good starting points. Or, if you don't mind giving away your source code, you could just deliver a collection of source files to your client.
In terms of developing the API itself, it should be very similar to the way you'd design interfaces and implementations of Objective-C objects in your own apps. You'll have a MyAPI class with functions for initialization, destruction, and all the functionality you want. You could also have multiple classes with different functionality if the interface is complex. Because you've capitalized MyAPI in your code snippet, it looks like you want to use it by calling the class rather than an instance of the class - which is a great strategy if you think you'll only ever need one instance. To accomplish this you can use the singleton pattern.
Because you've used a username and password, I imagine your API will interface with the web internally. I've found parsing JSON to be very straightforward in Objective-C - it's easy to send requests and get information from a server.
Personally I would use an enum of unsigned ints rather than a NSString just because it simplifies comparisons and such. So you could do something like:
enum {
MYAPI_MODE_BETA,
MYAPI_MODE_LIVE,
NUM_MYAPI_MODES
};
And then call:
[MyAPI username:#"Username" password:#"Password" mode:MYAPI_MODE_BETA];
Also makes it easy to check if they've supplied a valid mode. (Must be less than NUM_MYAPI_MODES.)
Good luck!

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.