How will neo4j jdbc (bolt) handle queries that return a list of nodes? - jdbc

In neo4j jdbc (bolt), Node is returned as Map , but if you make a query that returns a list of Nodes, getObject () will return a list of InternalNodes. Entities in this list can not be identified by type instanceof, so reflection will identify the node by type name and you will get the value by calling the method by reflection.You can get the value by doing the following, but is this approach correct? rs is ResultSet.entity is return value of this method.
Object columnObject = rs.getObject(columnName);
if (columnObject instanceof List<?>){
List<Map<String,Object>> objectValue = arrayList();
Array columnArray = rs.getArray(columnName);
Object[] columnArrayValues = (Object[]) columnArray.getArray();
for (int iTmp = 0; iTmp < columnArrayValues.length; iTmp++){
Map<String, Object> colArrayItemMap = new HashMap<>();
Object colItemObj = columnArrayValues[iTmp];
Class colItemClass = colItemObj.getClass();
if (colItemClass.getName().equals("org.neo4j.driver.internal.InternalNode")){
Method asMap = colItemClass.getMethod("asMap");
Method getId = colItemClass.getMethod("id");
Method getLabels = colItemClass.getMethod("labels");
colArrayItemMap.put("_id", getId.invoke(colItemObj));
colArrayItemMap.put("_labels", getLabels.invoke(colItemObj));
colArrayItemMap.putAll((Map<? extends String, ?>) asMap.invoke(colItemObj));
} else {
colArrayItemMap.put("_raw", columnArrayValues[iTmp]);
}
objectValue.add(colArrayItemMap);
}
((Map) entity).put(propertyName, objectValue);
} else {
((Map) entity).put(propertyName, columnObject);
}
Such queries are generated by such cypher statements.Such queries are generated by such cypher statements.
MATCH
(input:Input),
(output:Output)
WITH input, output
MATCH
(input)-[:INPUT*1]->(in),
(out)-[:OUTPUT*1]->(output),
g = (in)-[connect:CONNECT*0..5]->(out)
RETURN
input, output, extract(x IN nodes(g)|x) as nodes

It was for different class loaders that we can not identify with the instanceof operator.Since the jdbc driver was placed in Tomcat / lib, it was judged to be different from the class loaded by the application.
In any case, it will be provided by converting List to List or until getResults() is supported as the return value of getArray() It is thought that it is necessary to write.

Related

Gson.toJsonTree(intValue) throws Null pointer exception when trying to pass Integer parameter value

We are automating rest APIs using Rest Assured. During this process, trying to have a re-usable method created to pass different JSON nodes with different values.
Interger variable created:
Integer amt = 50;
Method created:
public void replaceValues_gson(String mainNode, String childNode, Integer amt) {
if(amt != null){
jsonObjectNew.getAsJsonObject("mainNode").add("childNode", gson.toJsonTree(amt));
}
//here 'amt' throws an error as java.lang.NullPointerException; Also the amt it shows as 9 assigned to variable amt in the debugger where as it supposed to assign 50 value
}
Calling above method as:
replaceValues_gson("bInfo", "bEx", amt );
Request JSON payload for the above is:
{
"bInfo":{
"bEx":9,
"oriDate":"2020-07-08"
}
}
Getting NullPointerException for 'amt' variable and Request JSON payload value is getting assigned rather assigning Integer amt value which is 50.
It works if directly trying like below:
jsonObjectNew.getAsJsonObject("bInfo").add("bEx", gson.toJsonTree(amt));
here amt variable value correctly goes as 50, but when trying to create re-usable method then throws an error.
Please guide.
You can use the following method. But it does not support when the value that need to be updated is inside a json array.
public void replaceValues_gson(JsonObject jsonObjectNew, String[] keyArray, Object updatingValue) {
Gson gson = new Gson();
JsonObject jsonObject = jsonObjectNew;
for (int i = 0; i < keyArray.length - 1; i++) {
jsonObject = jsonObject.getAsJsonObject(keyArray[i]);
}
jsonObject.add(keyArray[keyArray.length - 1], gson.toJsonTree(updatingValue));
System.out.println(jsonObjectNew.toString());
}
Here;
jsonObjectNew - the JsonObject converted from initial json request.
keyArray - String array of json node names from the root (in the exact order) including the key that need to be updated
updatingValue - value that will be updated
Eg:-
String[] keyArray = {"bInfo", "bEx"};
replaceValues_gson(jsonObjectNew, keyArray, 50);

How to use ES Java API to create a new type of an index

I have succeed create an index use Client , the code like this :
public static boolean addIndex(Client client,String index) throws Exception {
if(client == null){
client = getSettingClient();
}
CreateIndexRequestBuilder requestBuilder = client.admin().indices().prepareCreate(index);
CreateIndexResponse response = requestBuilder.execute().actionGet();
return response.isAcknowledged();
//client.close();
}
public static boolean addIndexType(Client client, String index, String type) throws Exception {
if (client == null) {
client = getSettingClient();
}
TypesExistsAction action = TypesExistsAction.INSTANCE;
TypesExistsRequestBuilder requestBuilder = new TypesExistsRequestBuilder(client, action, index);
requestBuilder.setTypes(type);
TypesExistsResponse response = requestBuilder.get();
return response.isExists();
}
however, the method of addIndexType is not effected, the type is not create .
I don't know how to create type ?
You can create types when you create the index by providing a proper mapping configuration. Alternatively a type gets created when you index a document of a certain type. However the first suggestion is the better one, because then you can control the full mapping of that type instead of relying on dynamic mapping.
You can set types in the following way:
// JSON schema is the JSON mapping which you want to give for the index.
JSONObject builder = new JSONObject().put(type, JSONSchema);
// And then just fire the below command
client.admin().indices().preparePutMapping(indexName)
.setType(type)
.setSource(builder.toString(), XContentType.JSON)
.execute()
.actionGet();

NHibernate returning results from Web API

I'm using Nhibernate to fetch a collection which has lazy loaded properties but am having trouble returning it as the Serializer tries to serialize the lazy property after the Nhibernate Session is closed. So is there a way to tell NHibernate to give me a true list in which if there were unloaded lazy collections that it would just leave them empty?
For example
IEnumerable<Store> stores = StoreService.GetList(1, 2);
Store has a one-to-many mapping with StockItems which is set to lazy load which then causes the serialization error. I tried
List<Store> stores_r = stores.ToList();
but I get the same thing. Is there something that will traverses through the list and fetches one-to-one relations and ignores one-to-many lazy loading and return a finished list?
Thanks
EDIT:Solution I've tried but still not working
public class NHibernateContractResolver: DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType) || typeof(NHibernate.Proxy.ILazyInitializer).IsAssignableFrom(objectType))
{
var oType = objectType.GetInterfaces().FirstOrDefault(i => i.FullName.StartsWith("Navace.Models"));
return oType != null ? base.CreateContract(oType) : base.CreateContract(objectType.BaseType);
}
return base.CreateContract(objectType);
}
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))
{
return base.GetSerializableMembers(objectType.BaseType);
}
else
{
return base.GetSerializableMembers(objectType);
}
}
}
Try to manually serialize so I can use what's happening
IEnumerable<Store> stores = StoreService.GetList(1, 2);
Store> storess = stores.ToList();
JsonSerializer sr = new JsonSerializer
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new NHibernateContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
};
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter);
sr.Serialize(jsonWriter, storess);
string res = stringWriter.ToString();
The error I get is
Outer exception : Error getting value from 'datedcost' on 'PartProxy'.
Inner exception: No row with the given identifier exists[Navace.Models.Part#0]
My recommendation is to return view models instead of domain models. It's confusing to return an empty collection property when it may have data. By converting the domain model to a view model (using LINQ Select or AutoMapper), the serializer will only touch (and attempt to lazy load) the properties in the view model.

Reflection + Linq + DbSet

I use EF code-first 4.1. in my application. Now I want to get entities through WCF services using generic types.
I'm trying to reflect generic type and invoke the method ToList of DbSet Object.
Here is my code:
public string GetAllEntries(string objectType)
{
try
{
var mdc =
Globals.DbConnection.Create(#"some_db_connection", true);
// Getting assembly for types
var asob = Assembly.GetAssembly(typeof(CrmObject));
// getting requested object type from assembly
var genericType = asob.GetType(objectType, true, true);
if (genericType.BaseType == typeof(CrmObject))
{
// Getting Set<T> method
var method = mdc.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();
// Making Set<SomeRealCrmObject>() method
var genericMethod = method.MakeGenericMethod(genericType);
// invoking Setmethod into invokeSet
var invokeSet = genericMethod.Invoke(mdc, null);
// invoking ToList method from Set<> invokeSet
var invokeToList = invokeSet.GetType().GetMember("ToList").Cast<MethodInfo>().FirstOrDefault();
//this return not referenced object as result
return invokeToList.ToString();
}
return null;
}
catch (Exception ex)
{
return ex.Message + Environment.NewLine + ex.StackTrace;
}
}
In fact then I write the code like return mdc.Set<SomeRealCrmObject>().ToList() - works fine for me! But then I use the generic types I cannot find the method ToList in object DbSet<SomeRealCrmObject>().
Eranga is correct, but this is an easier usage:
dynamic invokeSet = genericMethod.Invoke(mdc, null);
var list = Enumerable.ToList(invokeSet);
C# 4's dynamic takes care of the cumbersome generic reflection for you.
ToLIst() is not a member of DbSet/ObjectSet but is an extension method.
You can try this instead
var method = typeof(Enumerable).GetMethod("ToList");
var generic = method.MakeGenericMethod(genericType);
generic.Invoke(invokeSet, null);
I had a similar situation where I needed a way to dynamically load values for dropdown lists used for search criteria on a page allowing users to run adhoc queries against a given table. I wanted to do this dynamically so there would be no code change on the front or backend when new fields were added. So using a dynamic type and some basic reflection, it solved my problem.
What I needed to do was invoke a DbSet property on a DbContext based on the generic type for the DbSet. So for instance the type might be called County and the DbSet property is called Counties. The load method below would load objects of type T (the County) and return an array of T objects (list of County objects) by invoking the DbSet property called Counties. EntityList is just a decorator object that takes a list of lookup items and adds additional properties needed for the grid on the front-end.
public T[] Load<T>() where T : class
{
var dbProperty = typeof(Data.BmpDB).GetProperties().FirstOrDefault(
x => x.GetMethod.ReturnType.GenericTypeArguments[0].FullName == typeof(T).FullName);
if (dbProperty == null)
return null;
dynamic data = dbProperty.GetMethod.Invoke(BmpDb, null);
var list = Enumerable.ToList(data) as List<T>;
var entityList = new Data.EntityList<T>(list);
return entityList.Results;
}

How to access data into IQueryable?

I have IQueryable object and I need to take the data inside the IQueryable to put it into Textboxs controls. Is this possible?
I try something like:
public void setdata (IQueryable mydata)
{
textbox1.text = mydata.????
}
Update:
I'm doing this:
public IQueryable getData(String tableName, Hashtable myparams)
{
decimal id = 0;
if (myparams.ContainsKey("id") == true)
id = (decimal)myparams["id"];
Type myType= Type.GetType("ORM_Linq." + tableName + ", ORM_Linq");
return this.GetTable(tableName , "select * from Articu where id_tipo_p = '" + id + "'");
}
public IQueryable<T> GetTable<T>(System.Linq.Expressions.Expression<Func<T, bool>> predicate) where T : class
{
return _datacontext.GetTable<T>().Where(predicate);
}
This returns a {System.Data.Linq.SqlClient.SqlProvider+OneTimeEnumerable1[ORM_Linq.Articu]}`
I don't see any method like you tell me. I see Cast<>, Expression, ToString...
EDIT: Updated based on additional info from your other posts...
Your getData method is returning IQueryable instead of a strongly typed result, which is why you end up casting it. Try changing it to:
public IQueryable<ORM_Linq.Articu> getData(...)
Are you trying to query for "Articu" from different tables?
With the above change in place, your code can be rewritten as follows:
ORM_Linq.Articu result = mydata.SingleOrDefault();
if (result != null)
{
TextBoxCode.Text = result.id.ToString();
TextBoxName.Text = result.descrip;
}
If you have a single result use SingleOrDefault which will return a default value if no results are returned:
var result = mydata.SingleOrDefault();
if (result != null)
{
textbox1.text = result.ProductName; // use the column name
}
else
{
// do something
}
If you have multiple results then loop over them:
foreach (var item in mydata)
{
string name = item.ProductName;
int id = item.ProductId;
// etc..
}
First, you should be using a strongly-typed version of IQueryable. Say that your objects are of type MyObject and that MyObject has a property called Name of type string. Then, first change the parameter mydata to be of type IQueryable<MyObject>:
public void setdata (IQueryable<MyObject> mydata)
Then we can write a body like so to actually get some data out of. Let's say that we just want the first result from the query:
public void setdata (IQueryable<MyObject> mydata) {
MyObject first = mydata.FirstOrDefault();
if(first != null) {
textbox1.Text = first.Name;
}
}
Or, if you want to concatenate all the names:
public void setdata(IQueryable<MyObject> mydata) {
string text = String.Join(", ", mydata.Select(x => x.Name).ToArray());
textbo1.Text = text;
}
Well, as the name suggests, an object implementing IQueryable is... Queryable! You'll need to write a linq query to get at the internal details of your IQueryable object. In your linq query you'll be able to pull out its data and assign bits of it where ever you'd like - like your text box.
Here's a great starting place for learning Linq.
I think you find the same mental struggle when coming from FoxPro and from DataSet. Really nice, powerful string-based capabilities(sql for query, access to tables and columns name) in these worlds are not available, but replaced with a compiled, strongly-typed set of capabilities.
This is very nice if you are statically defining the UI for search and results display against a data source known at compile time. Not so nice if you are trying to build a system which attaches to existing data sources known only at runtime and defined by configuration data.
If you expect only one value just call FirstOrDefault() method.
public void setdata (IQueryable mydata)
{
textbox1.text = mydata.FirstOrDefault().PropertyName;
}

Resources