samedi 30 avril 2022

Reflection: how to assign an Array to Object's field

I use readValue of Jackson framework which returns Object[] (valueField). And I have an object bean with the field List<T> repository (targetField). I need to assign Array to that List, but the best I reached is that targetField holds 1 element which is the whole Array itself (look at attached image).

I tried to cast Object[] to List but I got ImmutableCollectionList instead of common array and targetField is just assigned the reference instead of value. New ArrayList() does not help. I tryed field.set(bean, valueField) with no result and ran into Array.newInstance(), but did not managed to implement it correctly in that case. I'm puzzled

private void installFieldConfig(Object bean, Field field) {
    ConfigProperty configProperty = field.getAnnotation(ConfigProperty.class);
    File file = configProperty.configFileNameEnum().getConfigFile();

    Object targetField;
    Object valueField;
    if (AbstractDao.class.isAssignableFrom(bean.getClass())) {
        Class<?> singleClazz = ((AbstractDao<?>) bean).getTypeParameterClass();
        Class<?> arrayClazz = Array.newInstance(singleClazz, 0).getClass();
        try {
            targetField = field.get(bean); //successfully get the bean's field in which I want inject new value (ArrayList<T>)
            valueField = objectMapper.readValue(file, arrayClazz); //this is Jackson method, returns T[] 
            targetField = List.of(valueField); //here is the trouble
            field.set(bean, valueField); //also trouble
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Debug overview image





vendredi 29 avril 2022

DbSet variable table name

I am writting an application where I need to abstract the DbSet table name. Instead of calling _db.Activities.ToList() (where Activity is a table in Sql) the code below will work for any variable table input.

Now I wanted to use .Where(),.OrderBy(),.FromSqlRaw() and other methods on top of the existing code.

How can I write _db.Activities.FromSqlRaw(...) for example, with a variable table name, just like it is doing for the GetAll method.

This is my DbSet for Activity

public virtual DbSet<Activity> Activities { get; set; } = null!;

This is the method to get all records from a variable table

public dynamic GetAll(string Table)
        {
            var curEntityPI = _db.GetType().GetProperty(Table);
            var curEntityType = curEntityPI.PropertyType.GetGenericArguments().First();
            // Getting Set<T> method
            var method = _db.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();
            // Making Set<SomeRealCrmObject>() method
            var genericMethod = method.MakeGenericMethod(curEntityType);
            // invoking Setmethod into invokeSet 
            dynamic invokeSet = genericMethod.Invoke(_db, null);
            // invoking ToList method from Set<> invokeSet 
            return Enumerable.ToList(invokeSet); 
        }

The general ideia comes from this post

https://ift.tt/if9Z0A5





Extract tags from Go struct as a reflect.Value

I'm trying to extract tags from a certain Value which is a struct. I am able to get the fields of the struct but unable to extract the tags. What am I doing wrong here? I've tried many different ways (using reflect.Type, interface{} etc) but all failed.


type House struct {
    Room string
    Humans Human
}

type Human struct {
    Name         string `anonymize:"true"` // Unable to get this tag
    Body         string
    Tail         string `anonymize:"true"` // Unable to get this tag
}

func printStructTags(f reflect.Value) { // f is of struct type `human`
    for i := 0; i < f.NumField(); i++ {
        fmt.Printf("Tags are %s\n", reflect.TypeOf(f).Field(i).Tag) // TAGS AREN'T PRINTED
    }
}

The reason I use reflect.Value as the parameter is because this function is called from another function in the following manner

    var payload interface{}
    payload = &House{}
    // Setup complete
    v := reflect.ValueOf(payload).Elem()
    for j := 0; j < v.NumField(); j++ { // Go through all fields of payload
        f := v.Field(j)
        if f.Kind().String() == "struct" { 
            printStructTags(f)
        }
    }

Any insights would be extremely valuable





Calling Java from Node.js

I'm trying to follow this simple tutorial about calling Java from Node.js:

My test script:

var java = require('java');
var javaLangSystem = java.import('java.lang.System');

javaLangSystem.out.printlnSync('Hello Java!');

Here is the console:

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
...
$ npm install java

added 18 packages, and audited 19 packages in 11s

1 package is looking for funding
  run `npm fund` for details

2 high severity vulnerabilities

To address all issues, run:
  npm audit fix

Run `npm audit` for details.
$ node test.js 
/home/Projects/test-java/node_modules/java/lib/nodeJavaBridge.js:240
  var fields = SyncCall(clazz, 'getDeclaredFields')();
                                                   ^

Error: Error running instance method
java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:208)
    at java.base/java.lang.invoke.MethodHandleImpl$1.reflectiveInvoker(MethodHandleImpl.java:1660)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:131)
    at java.base/java.lang.reflect.Method.invoke(Method.java:577)

    at Java.java.import (/home/Projects/test-java/node_modules/java/lib/nodeJavaBridge.js:240:52)
    at Object.<anonymous> (/home/Projects/test-java/test.js:2:33)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  cause: nodeJava_java_lang_NullPointerException {}
}
$ java --version
java 18.0.1 2022-04-19
Java(TM) SE Runtime Environment (build 18.0.1+10-24)
Java HotSpot(TM) 64-Bit Server VM (build 18.0.1+10-24, mixed mode, sharing)

What may be going wrong here?

I've tried to debug it and it seems that obj[syncMethodName].bind(obj) throws a java.lang.NullPointerException at java.base/java.lang.reflect.Method.invoke(Method.java:577) when

obj == class java.lang.System
syncMethodName == 'getDeclaredFieldsSync'




jeudi 28 avril 2022

C# InvokeMember - MissingMethodException: 'Method not found'

In a .NET Core 6 RestAPI application, I'm tracking global stock exchanges and have an instance of the below Exchange class called "ex".

public class Exchange
{
    public string CountryCode { get; set; }
    public string Currency { get; set; }
    public string DataSourceCode { get; set; }
    public int DaysHoursId { get; set; }
    public string ExchangeCode { get; set; }
    public string ExchangeName { get; set; }
    public int Id { get; set; }
    public bool IsActive { get; set; }
    public DateTimeOffset LastUpdatedDate { get; set; }
    public string LastUpdatedStatus { get; set; }
    public DateTimeOffset NextUpdateDateTime { get; set; }
    public string Region { get; set; }
    public string Timezone { get; set; }
    public string Type { get; set; }
    public string Url { get; set; }
    public string Website { get; set; }
}

All fields are populated with non-null data. In this case, the body of my Postman call is: { "CountryCode": "USA", "Currency": "USD", "DataSourceCode": "IA2", "DaysHoursId": 2, "ExchangeCode": "AMEX", "ExchangeName": "AMEX",
"IsActive": true, "LastUpdatedDate": "2022-04-24T15:42:28.2533333+00:00", "LastUpdatedStatus": "OK", "NextUpdateDateTime": "2022-04-24T15:42:28.2533333+00:00", "Region": "NORTH AMERICA", "Timezone": "EST", "Type": "STOCK", "Url": "https://ift.tt/IzBjKyl", "Website": "www.AMEX.com" }

Using Reflection, I create a DataTable from this object with all columns except for "Id", which is an Identity primary key in the table to which data will be loaded, as follows:

 PropertyDescriptorCollection props = TypeDescriptor.GetProperties(ex);
 DataTable dt = new DataTable();
 foreach (PropertyDescriptor p in props)
 {
      if (p.Name != "Id")  // insert into an identity column not allowed.
      { 
           dt.Columns.Add(p.Name, p.PropertyType);
      }
 }

I then attempt to create a row in the dt datatable, as follows:

DataRow dr = dt.NewRow();
Type t = ex.GetType();
for (int i = 0; i <= dt.Columns.Count; i++)
{
    t.InvokeMember(dt.Columns[i].ColumnName, System.Reflection.BindingFlags.SetProperty, null, ex, new object[] { dt.Columns[i].ColumnName });
}

... which, when executed and traced, InvokeMember successfully iterated through the CountryCode, Currency, and DataSourceCode columns, but then - when it reaches DaysHoursId - threw a "System.MissingMethodException: 'Method MarketApi.Core.Entitites.Exchange.DaysHoursId' not found' exception.

Any insight as to what I'm doing wrong would be very much appreciated!





mercredi 27 avril 2022

Creating Actions via reflection with type parameters to proxy call

Given a simple object

public class Foo {
   public void RunAction(Action<int, string, byte> action) {
        Action(0, null, 0);
   }
}

And given a sample pseudo-code method that reads this class to obtain the action type via reflection:

public void DoProxy(object [] calledWithParameters) {
     ... some code ...
}

public void DoReflection(Foo foo) {
   var actionParameterInfo = foo.getType().getMethod("RunAction").GetParameters()[0];
   var parameterTypes = actionParameterInfo.ParameterType.GenericTypeArguments;
   // Now I have the action type and the Type[] of the necessary parameters.
}

In this case how could I create dynamically an Action that calls my DoProxy with the received parameters on call ?





SDN RYU Controller-Read DNS Header Flags in DNS Amplification Reflection Attack

I implement an SDN network with an RYU controller. I simulate a DNS amplification reflection attack.

Now I need to recognize legitimate from illegitimate DNS responses by reading some flags in the DNS header.

Does anybody have an idea how it is possible to read DNS flags in the RYU controller?

Thank you