Allocating tuner on Frontend 2.0 compliant device in Java - redhawksdr

I'm developing a Frontend 2.0 interface compliant device using Redhawk 1.9 on RHEL 5. My implementation is using Java, and I have a test framework set up within JUnit to ease testing and metrics during development. I'm hoping to make an automated test that allocates a single available tuner by passing in a "FRONTEND::tuner_allocation" struct property. Using the answer to this question, I came up with the following code:
List<DataType> props = new LinkedList<DataType>();
props.add(new DataType("FRONTEND::tuner_allocation::tuner_type", AnyUtils.toAny("DDC", TCKind.tk_string)));
props.add(new DataType("FRONTEND::tuner_allocation::allocation_id", AnyUtils.toAny(allocId, TCKind.tk_string)));
props.add(new DataType("FRONTEND::tuner_allocation::center_frequency", AnyUtils.toAny(98700000.0, TCKind.tk_double)));
props.add(new DataType("FRONTEND::tuner_allocation::bandwidth", AnyUtils.toAny(200000.0, TCKind.tk_double)));
props.add(new DataType("FRONTEND::tuner_allocation::bandwidth_tolerance", AnyUtils.toAny(25.0, TCKind.tk_double)));
props.add(new DataType("FRONTEND::tuner_allocation::sample_rate", AnyUtils.toAny(200000.0, TCKind.tk_double)));
props.add(new DataType("FRONTEND::tuner_allocation::sample_rate_tolerance", AnyUtils.toAny(25.0, TCKind.tk_double)));
props.add(new DataType("FRONTEND::tuner_allocation::device_control", AnyUtils.toAny(true, TCKind.tk_boolean)));
props.add(new DataType("FRONTEND::tuner_allocation::group_id", AnyUtils.toAny("", TCKind.tk_string)));
props.add(new DataType("FRONTEND::tuner_allocation::rf_flow_id", AnyUtils.toAny("", TCKind.tk_string)));
DataType[] tunersToAllocate = new DataType[1];
tunersToAllocate[0] = new DataType("FRONTEND::tuner_allocation", AnyUtils.toAny(props, TCKind.tk_struct));
try
{
assertTrue(rhDevice.allocateCapacity(tunersToAllocate));
}
catch (InvalidCapacity invalidCapacity)
{
logger.error("Unexpected allocation failure (invalid capacity)", invalidCapacity);
assertTrue(invalidCapacity.getMessage(), false);
}
catch (InvalidState invalidState)
{
logger.error("Unexpected allocation failure (invalid state)", invalidState);
assertTrue(invalidState.getMessage(), false);
}
However, this results in a null pointer exception within the final AnyUtils.toAny() call, since the version of toAny() that takes TCKind apparently does not support non-primitive types:
java.lang.NullPointerException
at org.ossie.properties.AnyUtils.insertInto(AnyUtils.java:636)
at org.ossie.properties.AnyUtils.toAny(AnyUtils.java:606)
at org.ossie.properties.AnyUtils.toAny(AnyUtils.java:616)
at com.<company-name>.redhawk.nsi.test.NsiClientDeviceTest.testAllocateTuner(NsiClientDeviceTest.java:247)
Line 247 is the line with "toAny(props, TCKind.tk_struct)".
Looking at the AnyUtils class code, it seems I should be passing a TypeCode instead. However, I'm unsure how to get a TypeCode for a struct property, since the code for getComplexTypeCode() and getPrimitiveTypeCode() look like they both do not contain checks for struct types.
Am I going about this the wrong way entirely? If not, how do I indicate that I want to create an Any of type struct?

Struct properties are packed into CORBA Anys as CF.Properties, but unfortunately, there is no method in AnyUtils to do that. Instead, you have to create the Any and then insert your value into it. User-defined CORBA data types like CF.Properties have a generated helper class with insert and extract methods that work with Anys, while primitive types can be inserted or extracted via the Any's member functions.
The following code snippet creates an Any via the ORB and uses the static CF.PropertiesHelper.insert() method to store the properties in it:
org.omg.CORBA.Any tunerAlloc = org.omg.CORBA.ORB.init().create_any();
CF.PropertiesHelper.insert(tunerAlloc, props.toArray(new DataType[props.size()]));
tunersToAllocate[0] = new DataType("FRONTEND::tuner_allocation", tunerAlloc);
The generated CORBA helpers only work with arrays, so Java Collections types have to be converted (in the above example, it's done in-line). If you have your own ORB reference, you can use that instead of ORB.init().

Related

How can I call this jOOQ generated function taking a custom bound type?

I originally had the following SQL function:
CREATE FUNCTION resolve_device(query JSONB) RETURNS JSONB...
and the following code calling the method generated by jOOQ:
final JsonArray jsonArray = jooqDWH.select(resolveDevice(queryJson)).fetchOne().value1().getAsJsonArray();
final JsonObject o = jsonArray.get(0).getAsJsonObject();
This worked fine. I needed to return a real device object rather than a JSON blob though, so I changed the SQL function to:
CREATE FUNCTION resolve_device(query JSONB) RETURNS SETOF device...
and the code to:
final ResolveDeviceRecord deviceRecord = jooqDWH.fetchOne(resolveDevice(queryJson));
but I am getting a runtime error:
org.jooq.exception.SQLDialectNotSupportedException: Type class com.google.gson.JsonElement is not supported in dialect DEFAULT
Many other parts of my code continue to work fine with the custom binding I have converting JsonElement to JSONB, but something about the change to this function's signature caused it to stop working.
I tried a few different variants of DSL.field() and DSL.val() to try to force it to be recognized but have not had any luck so far.
This could be a bug in jOOQ or a misconfiguration in your code generator. I'll update my answer once it is clear what went wrong.
Workaround:
Meanwhile, here's a workaround using plain SQL:
// Manually create a data type from your custom JSONB binding first:
final DataType<JsonObject> jsonb = SQLDataType.OTHER.asConvertedDataType(jsonBinding);
// Then, create an explicit bind variable using that data type:
final ResolveDeviceRecord deviceRecord =
jooqDWH.fetchOptional(table("resolve_device({0})", val(queryJson, jsonb)))
.map(r -> r.into(ResolveDeviceRecord.class))
.orElse(null);

Why does my Groovy AST transform insert null at the end of my method?

I have written an AST transform that creates a setter for a JPA mapped property (it both sets the local field and calls setOwner on the other end of the relationship):
private static void createSetter(FieldNode field) {
Parameter parameter = GeneralUtils.param(field.getType(), field.getName());
BlockStatement body = new BlockStatement();
body.addStatement(assignS(fieldX(field), varX(parameter)));
MethodCallExpression setterCall = callX(varX(parameter), "setOwner", varX("this", field.getDeclaringClass()));
setterCall.setType(ClassHelper.VOID_TYPE);
body.addStatement(stmt(setterCall));
MethodNode method = new MethodNode(setterName(field.getName()), ACC_PUBLIC, ClassHelper.VOID_TYPE, new Parameter[] {parameter}, ClassNode.EMPTY_ARRAY, body);
field.getDeclaringClass().addMethod(method);
}
This works, but the generated method has a strange null statement at the end as disassembled by JD-GUI (in addition to an odd local variable):
public void setMore(Simple_MoreStuff more) {
Simple_MoreStuff localSimple_MoreStuff = more;
this.more = localSimple_MoreStuff;
more.setOwner(this);
null;
}
It doesn't seem to affect the actual correctness, but it's odd, and it seems like a bug. In MethodCallExpression, I found this comment but don't know if it relates, since my method is in fact void (I explicitly set it above, and it makes no difference):
//TODO: set correct type here
// if setting type and a methodcall is the last expression in a method,
// then the method will return null if the method itself is not void too!
// (in bytecode after call: aconst_null, areturn)
Is there a way to keep the generated method from having the spurious null?
I have not looked at JD-GUI, so I cannot tell how capable this tool is in understanding bytecode, that does not come from Java. But in general disassemblers can only somewhat show what Java code in that case might look like, by no means it is supposed to show correct code from a non-Java language. So better do not expect correct Java code if you disassemble Groovy.
In this case I suspect that JD-GUI stumbles over a workaround we have not gotten rid of yet. In several cases we add at the method end dead code, the const_null, areturn you have noticed. We do this because of problems with the verifier if a bytecode label is used at the end of a method. And since the dead code does not influence correctness we are currently using this solution.

ModelMapper Provider ignored on first level properties of a mapping

I have already successfully used a Provider in a ModelMapper transformation but I've stumbled upon a weird situation. I've noticed that the Provider is being considered only for the objects beyond the "first level" of the transformation, eg.:
I have two hierarchies:
1st) TipoConsultarProcessoResposta, TipoProcessoJudicial and TipoDocumento
2nd) ConsultarProcessoResposta, ProcessoJudicial and Documento
TipoConsultarProcessoResposta has a TipoProcessoJudicial that in turn has a List of TipoDocumento, the 2nd hierarchy ressembles the first.
I am converting from the first hierarchy to the second and the provider is working fine for the TipoDocumento to Documento conversion but it is being ignored for the conversion of TipoProcessoJudicial to ProcessoJudicial.
Here is the relevant part of the code:
modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(STRICT);
modelMapper.addMappings(new DocumentoPropertyMap()).setProvider(documentoProvider);
modelMapper.addMappings(new ProcessoJudicialPropertyMap()).setProvider(processoJudicialProvider);
ConsultarProcessoResposta resposta = modelMapper.map(tipoConsultarProcessoResposta, ConsultarProcessoResposta.class);
DocumentoPropertyMap extends PropertyMap<TipoDocumento, Documento> and ProcessoJudicialPropertyMap extends PropertyMap<TipoProcessoJudicial, ProcessoJudicial>.
The thing is that the DocumentoProvider is being called but ProcessoJudicialProvider isn't being called. ModelMapper tries to invoke a Global Provider that fails as well and resorts to instantiating through the constructor.

Cairo.Surface is leaking... How to debug it with Monodevelop?

I have many doubts related with Cairo and GTK# (that runs on .NET and Mono). I'm developing a GTK# application for MS Windows and Linux. I'm using GTK# 2.12 over .NET right now while I'm working on the application.
I've created a custom widget that uses Cairo.ImageSurface and Cairo.Context objects. As far as I know, I'm calling the Dispose method of every ImageSurface object and every Context object I create inside the widget code.
The widget responds to the "MouseOver" event, redrawing some parts of its DrawingArea.
The (first) problem:
almost every redrawing operation increases a little bit the amount of used memory. When the amount of used memory has increased 3 or 4 Kbytes the Monodevelop tracelog panel shows me the following message:
Cairo.Surface is leaking, programmer is missing a call to Dispose
Set MONO_CAIRO_DEBUG_DISPOSE to track allocation traces
The code that redraws a part of the widget is something like:
// SRGB is a custom struct, not from Gdk nor Cairo
void paintSingleBlock(SRGB color, int i)
{
using (Cairo.Context g = CairoHelper.Create (GdkWindow)) {
paintSingleBlock (g, color, i);
// We do this to avoid memory leaks. Cairo does not work well with the GC.
g.GetTarget().Dispose ();
g.Dispose ();
}
}
void paintSingleBlock(Cairo.Context g, SRGB color, int i)
{
var scale = Math.Pow (10.0, TimeScale);
g.Save();
g.Rectangle (x(i), y(i), w(i), h(i));
g.ClosePath ();
g.Restore ();
// We don't directly use stb.Color because in some cases we need more flexibility
g.SetSourceRGB (color.R, color.G, color.B);
g.LineWidth = 0;
g.Fill ();
}
The (second) problem: Ok, Monodevelop tells me that I should set MONO_CAIRO_DEBUG_DISPOSE to "track allocation traces" (In order to find the leak, I suppose)... but I don't know how to set this environment variable (I'm in Windows). I've tried using bash and executing something like:
MONO_CAIRO_DEBUG_DISPOSE=1 ./LightCreator.exe
But nothing appears in stderr nor stdout... (neither the messages that appear in the Monodevelop's applicationt trace panel). I also don't know how to get the debugging messages that see inside Monodevelop but without Monodevelop.
There's anyone with experience debugging GTK# or Cairo# memory leaks?
Thanks in advance.
Just wanted to throw my 2c here as I was fighting a similar leak problem in Cairo with surfaces. What I noticed is that if I create a Surface object the ReferenceCount property becomes 1 and if I attach this surface to a Context if becomes not 2 but 3. After disposing the Context the ReferenceCount comes back but to 2.
So I used some reflection to call the native methods in Cairo to decrease the ReferenceCount when I really want to Dispose a surface. I use this code:
public static void HardDisposeSurface (this Surface surface)
{
var handle = surface.Handle;
long refCount = surface.ReferenceCount;
surface.Dispose ();
refCount--;
if (refCount <= 0)
return;
var asm = typeof (Surface).Assembly;
var nativeMethods = asm.GetType ("Cairo.NativeMethods");
var surfaceDestroy = nativeMethods.GetMethod ("cairo_surface_destroy", BindingFlags.Static | BindingFlags.NonPublic);
for (long i = refCount; i > 0; i--)
surfaceDestroy.Invoke (null, new object [] { handle });
}
After using it I still have some leaks, but they seem to be related to other parts of Cairo and not with the surfaces.
I have found that a context created with CairoHelper.Create() will have a reference count of two.
A call to dispose reduces the reference count by one. Thus the context is never freed and keeps its target alive, too.
The native objects have manual reference counting, but the Gtk# wrappers want to keep a native object alive as long as there is a C# instance referencing it.
If a native object is created for a C# wrapper instance it does not need to increment the reference count because the wrapper instance 'owns' the native object and the reference count has the correct value of one. But if a wrapper instance is created for an already existing native object the reference count of the native object needs to be manually incremented to keep the object alive.
This is decided by a bool parameter when a wrapper instance is created.
Looking at the code for CairoHelper.Create() will show something like this
public static Cairo.Context Create(Gdk.Window window) {
IntPtr raw_ret = gdk_cairo_create(window == null ? IntPtr.Zero : window.Handle);
Cairo.Context ret = new Cairo.Context (raw_ret, false);
return ret;
}
Even though the native context was just created 'owned' will be false and the C# context will increment the reference count.
There is no fixed version right now, it can only be corrected by fixing the source and building Gtk# yourself.
CairoHelper is an auto-generated file, to change the parameter to true this attribute must be included in gdk/Gdk.metadata.
<attr path="/api/namespace/class[#cname='GdkCairo_']/method[#name='Create']/return-type" name="owned">true</attr>
Everything to build Gtk# can be found here.
https://github.com/mono/gtk-sharp

InstallShield calling advapi32.dll method type mismatch error

I am trying to call Advapi32.LsaOpenPolicy() from basic MSI InstallShield code. I've successfully called other avdapi32.dll methods; But LsaOPenPolicy is throwing a mismatched type error.
My prototype is:
prototype INT Advapi32.LsaOpenPolicy(POINTER, POINTER, INT, POINTER);
The windows definition is:
NTSTATUS LsaOpenPolicy(
_In_ PLSA_UNICODE_STRING SystemName,
_In_ PLSA_OBJECT_ATTRIBUTES ObjectAttributes,
_In_ ACCESS_MASK DesiredAccess,
_Inout_ PLSA_HANDLE PolicyHandle
);
I've noted in C++ samples that the ObjectAttriibute structure is zeroed out. So I do something similar here in the InstallShield code -- pArray points to the array contents.
for i = 0 to 11
array(i) = 0;
endfor;
array(0) = 24;
// current error is 80020005 type mismatch.
try
i = POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES;
pArray = array;
pPolicy = NULL;
nvOSResult = LsaOpenPolicy(NULL, pArray, i, pPolicy);
catch
Sprintf(errString, "0x%08x", Err.Number);
_Logger(hMSI, methodName, "LsaOpenPolicy Exception "+errString, INFORMATION, FALSE);
nvOSResult = Err.Number;
endcatch;
There not much other information I can find other than the 80020005 error thrown; I've tried a few different argument constructions, but I can't get past this.
I've posted this in an flexera and microsoft forum -- but I have gotten no traction there. (references for posterity: flexera-link, microsoft-link)
Any help or suggestions are welcome!
The answer to this question was to actually work-around the interface between installshield and the system DLLs by moving all the workings into a C++ DLL. As installation got more complex, I ended up with two separate DLL functions, one executed at dialog (non-admin) mode and one at deferred execution (admin) mode.
In order to pass information I used the MsiGetProperty() API using MSI properties for both input and output variables.
Note that for deferred execution, I needed a CAD function on the installshield side to marshal data into the custom action data location, and on the DLL side extract the data, again by using MsiGetProperty() but getting the "CustomActionData" property and then parse the resulting string which contained the marshaled data.

Resources