lundi 17 septembre 2018

Read JSON Nested element using reflection NOT JsonFactoy and ObjectMapper

[Unable to access property of another object stored in Arraylist] I am creating an function to get JSON input in object from RESTful Web service input and format it again in JSON format to call other web service.

I have limitation that I can not use any JSON API for object mapping hence using Java reflection core API.

I am able to create JSON format from Input for simple elements but unable to access nested elements (another user defined POJO class ). I am using arraylist.

Input

{
  "GenesisIncidents": {
"service": "Transmission",
"affectedCI": "22BT_ORNC03",
"opt_additionalAffectedItems": [
   {
      "itemType": "NODE-ID",
      "ItemName": "22BT_ORNC03"
   },
   {
      "ItemType": "CCT",
      "ItemName": "A_circuit_id"
        }]   
}
}

GenesisIncidents.class

import java.util.ArrayList;
import java.util.Date;
public class GenesisIncidents {

private String service;
private String affectedCI;
private ArrayList<AdditionalAffectedItems> opt_additionalAffectedItems;

public GenesisIncidents(){}

public String getService() {
    return service;
}

public void setService(String service) {
    this.service = service;
}

public String getAffectedCI() {
    return affectedCI;
}

public void setAffectedCI(String affectedCI) {
    this.affectedCI = affectedCI;
}


public ArrayList<AdditionalAffectedItems> getOpt_additionalAffectedItems() {
    return opt_additionalAffectedItems;
}
public void setOpt_additionalAffectedItems(ArrayList<AdditionalAffectedItems> opt_additionalAffectedItems) {
    this.opt_additionalAffectedItems = opt_additionalAffectedItems;
}
}

AdditionalAffectedItems.class

public class AdditionalAffectedItems {

private String itemType;
private String itemName;

public AdditionalAffectedItems(){
    super();
}

public String getItemType() {
    return itemType;
}

public void setItemType(String itemType) {
    this.itemType = itemType;
}

public String getItemName() {
    return itemName;
}

public void setItemName(String itemName) {
    this.itemName = itemName;
}
}

Implemetation

public void updateTicketExt(GenesisIncidents genesisIncidents) {
        try{

            Field allFields[]=genesisIncidents.getClass().getDeclaredFields();
            Method allMethods[] = genesisIncidents.getClass().getDeclaredMethods();
            String jsonString ="{\r\n \""+genesisIncidents.getClass().getName().toString().substring(48)+"\": {";
            final String preStr="\r\n  \"";             //To create a JSON object format.
            final String postStr="\": ";                //To create a JSON object format.
            int totalNoOfFields=allFields.length;

            for (Field field : allFields) {
                System.out.println(field.getType());
                String getter="get"+StringUtils.capitalize(field.getName());
                Method method= genesisIncidents.getClass().getMethod(getter, null);
                try{

                        if(field.getType().toString().contains("Integer"))
                            jsonString=jsonString + preStr + field.getName() + postStr +method.invoke(genesisIncidents).toString()+",";
                        else
                            jsonString=jsonString + preStr + field.getName() + postStr +"\""+method.invoke(genesisIncidents).toString()+"\",";

                        if(field.getType().toString().contains("ArrayList")){
                            System.out.println("ArrayListElement found");
                            genesisIncidents.getOpt_additionalAffectedItems().forEach(obj->{System.out.println(obj.getItemName());});
                            //convertArrayToJSON(field, genesisIncidents);
                        }

                }catch(NullPointerException npe)
                {
                    System.out.println("Null value in field.");
                    continue;
                }
                }
                jsonString=jsonString.substring(0,jsonString.length()-1);
                jsonString=jsonString+"\r\n }\r\n }";
                System.out.println("\n"+jsonString);
            }catch(Exception jex){
            jex.printStackTrace();
        }

    }

My below code line is unable to access object stored under array list.

genesisIncidents.getOpt_additionalAffectedItems().forEach(obj->{System.out.println(obj.getItemName());});

OUTPUT

karaf@root>class java.lang.String
class java.lang.String
class java.lang.String
class java.util.ArrayList
ArrayListElement found
null
null
{
 "GenesisIncidents": {
  "service": "Transmission",
  "affectedCI": "22BT_ORNC03",
  "opt_additionalAffectedItems": "    [org.apache.servicemix.examples.camel.rest.model.AdditionalAffectedItems@5881a    895,     org.apache.servicemix.examples.camel.rest.model.AdditionalAffectedItems@399b4e    eb]"
 }
 }





C# - How do I get a list of classes with specific custom attributes having set their properties to a certain custom type? [duplicate]

This question already has an answer here:

I have two classes...

  public enum MyType
            {
                type1,
                type2
            }


   [Sample(MyType.type2)]
    public class Person
    {

    }

    [Sample(type = MyType.type1)]
    public class People
    {

    }

and an attribute class ...

[AttributeUsage(AttributeTargets.All)]
      public class SampleAttribute : Attribute
{
    private MyType type { get; set; } = MyType.type1;
    public SampleAttribute(MyType _type)
    {
        type = _type;
    }
}

and following code into the Form_Load event...

var types = from t in Assembly.GetExecutingAssembly().GetTypes() select t;

            foreach (Type type in types)
            {
                if (type.GetCustomAttribute<SampleAttribute>().type == MyType.type1)
                {
                    listBox1.Items.Add(type.Name);
                }
            }

I wish to get a list of such classes for which I have set the custom attribute's property to type1

This code generates a run-time error saying..."object reference not set to an instance of an object"

Any suggestion? where and what I have missed to initialize? Thank you in advance.





dimanche 16 septembre 2018

How can we mock private methods without using power mockito

Can we mock private methods without using powermockito. I know it is possible though powermockito but just wanted to check with all, is it possible by some other means. Thanks -Sam





Using a security manager with reflection accessing a jar file

After implementing my platform to have the ability to load jar files dynamically using reflection, I come across a security issue. The jar file could be 'dangerous' and contain code that could effect things, therefore I come across on SO the use of using a SecurityManager.

I am loading the jar file like this (example of hard coded file):

URLClassLoader clsLoader = URLClassLoader
    .newInstance(new URL[] { new URL("file:/C://Temp/SettingsApp.jar") });
Class<?> cls = clsLoader.loadClass("iezon.app.SettingsApp");
JPanel settingsApp = (JPanel) cls.newInstance();

I have tried to use the SecurityManager like so:

try {
    SecurityManager sm = new SecurityManager();
    Object context = sm.getSecurityContext();
    sm.checkPermission(new AllPermission(), context);
    settingsAppPanel = (JPanel) cls.newInstance();
} catch (AccessControlException e) {
    e.printStackTrace();
}

The test with AllPermission() works and gives me this exception:

java.security.AccessControlException: access denied ("java.security.AllPermission" "" "")

However, I am unable to find any information on how to bind the jar file to this security manager and not the current platform. I just don't want the jar file to be able to open sockets, etc.. without firstly requesting permissions that the user can then accept.

I stumbled across BasicPermission, however, this is an abstract class and cannot be instanced like the AllPermission and likewise, I am unable to find any information on approaching this. Any help would be appreciated!





Find Kotlin classes implementing an interface

I am in the process of developing an application (Parser Application) where we have a parser class which is responsible for actually parsing the work.

I want to provide an extension point to all who want to use the API (beside the some generic parsing which I will provide as part of the API). The idea is to create an interface and if any one wants to declare their class as parser class, all they have to do is, to (declare to) implement the interface.

Then, I want to get the list of all the classes with its instance, implementing that parser. After that, I want to call the method of the base interface, which will be implemented by the user.





samedi 15 septembre 2018

How can I convert a Parameter Expression into a function?

If I have a dynamically created ParameterExpression:

class Product
{
    public string Name { get; set; }
}

var propertyName = "Name";

var propertyType = typeof(Product).GetProperty(propertyName).PropertyType;
var parameterExpression = Expression.Parameter(propertyType , propertyName);

How can I covert it into a Func<Product, TPropertyType>?

I specifically want to pass this into the Where or OrderBy linq methods used by entity framework.

I'm also open to other suggestions not using Expressions, but I highly doubt it's possible.





Create and invoke a function in run time, C#

there is a way to create and invoke a function in run time? for instance, how could I do to invoke this function?

    string function = @"public void Test(int num1, int num2)
        {
            int sum = num1 + num2;
            MessageBox.Show(sum.ToString());
        }";

        System.Reflection.MethodInfo method = null; // some code to create a method info from the string function
        method.Invoke(this, new object[] { 10, 20 });

All I could find were samples of System.Reflection.Emit.DynamicMethod, but none use a function in a string