Java MongoDb driver serialization works in UpdateOne but not when i call toJson - mongodb-java

I am updating a record on my mongoDb database.
The update is performed in a wrapper for a series of reason, it goes like:
Contact contact = generateContact();
UpdateResult updateResult = performUpdateOne("collection",new Document("field",fieldValue), new Document("$push", new Document("contacts", contact)),updateOptions);
Please keep in mind the new Document("$set", new Document("contacts", contact)) parameter because is the only mongoDb document that contains a reference to a Pojo, this field is used in the the method performUpdateOne
private UpdateResult performUpdateOne(String collectionName, Document filter, Document set, UpdateOptions updateOptions) {
...
...
LOG.debugf("Performing MongoDb UpdateOne command, collection[%s] query[%s] update[%s].", collectionName, filter.toJson(), set.toJson());
UpdateResult updateResult = collection.updateOne(filter, set, updateOptions);
The set.toJson() call gives me the exception:
Exception: : org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class ...Contact. at org.bson.internal.CodecCache.lambda$getOrThrow$1(CodecCache.java:52)
If I comment the LOG:debugf line the collection.updateOne(filter, set, updateOptions) gives me no problem.
Why is the set document serialized correctly in the updateOne method while giving an error when i call .toJson() on it?
Thanks a lot
I am using mongo sync java driver 4.3.4

Related

Why is elasticsearch's Nest lowlevel Search method ignoring type and index name defined in SearchDescriptor<>() object

NEST/Elasticsearch.Net version:5.6.5
Elasticsearch version:5.4.3
We are trying to fetch result from our index using the LowLevelClient. We are using the below SearchAsync API
var searchDescriptor = new SearchDescriptor<MyType>()
.Type("mytype")
.Index("myindex")
.Query(....)
.Aggregation(ag => ag.Terms(... Aggregation(ag1 => ag1.Min(...TopHits(...)))));
var memoryStream = new MemoryStream();
_client.Serializer.Serialize(searchDescriptor, memoryStream);
var response = await _client.LowLevel.SearchAsync<byte[]>(memoryStream.ToArray()).ConfigureAwait(false);
//_client - instance of Nest.ElasticClient
//Next Step - Deserialize the response
This is giving me results from other indices also(a combination of results from the various indices) and my deserialization is breaking. The client is ignoring type and index name and calling POST /_search API instead of POST /myindex/mytype/_search on the elastic search
Note:
We need to call a lower-level client because we are using a custom deserializer for performance concern
What is the issue here?
Found a workaround
The SearchAsync<>() method have overloaded method _client.LowLevel.SearchAsync<T>(string indexName, string typeName, T t)
Passing the index name and type name will narrow to search to that particular index.
But the question still remains, why it is not taking the index and type name from SearchDescriptor object.

Elasticsearch's NEST API does not return query results while the same query is successful when submitting by POSTMAN

The following code snippet is a MoreLikeThis query built using NEST API:
private class Temp
{
public string Content { get; set; }
public string TextToSearch { get; set; }
}
var temp = new Temp
{
TextToSearch = "empire",
};
var response = await model.ElasticClient.SearchAsync<Temp>(s => s
.Query(q => q
.MoreLikeThis(qd => qd
.Like(l => l.Text(temp.TextToSearch))
.MinTermFrequency(1)
.MinDocumentFrequency(1)
.Fields(fd => fd.Fields(r => r.Content)))));
After executing this code snippet response.Documents did not return any records. But when the following JSON payload is POSTed by POSTMAN, the results are received successfully:
{"query":{"more_like_this":{"fields":["content"],"like":["advanced technology"],"min_doc_freq":1,"min_term_freq":1}}}
This payload is generated by the C# code snippet above when enabling audit trail. While the credentials are passed in both cases properly why the NEST API version 6.5.0 does not receive documents from the elastic search instance?
Is there a bug in the library or we're missing a point?
Besides the TextToSearch being "empire" in the C# example and "advanced technology" in the JSON query DSL example, I strongly suspect that the issue here is that of the index and type being targeted in the NEST case.
When no index and type are provided in the API call:
For index,
Will look to see if there is a default index to use for Temp type configured with DefaultMappingFor<T> on ConnectionSettings
If no default index for Temp, will use the DefaultIndex configured on ConnectionSettings
If no default index is configured on ConnectionSettings, the API call will not be made and NEST will throw an exception to indicate that it does not have enough information to make the API call.
For type,
Will look to see if there is a default type name to use for Temp type configured with DefaultMappingFor<T> on ConnectionSettings
Will look to see if a type name convention is configured using DefaultTypeNameInferrer on ConnectionSettings. If none is configured, or the delegate it is configured with returns null or "" for a given type, then will continue
Will look to see if a default type name is specified with DefaultTypeName on ConnectionSettings. If none is specified, a type name will be inferred for a POCO type by lowercasing the type name. For Temp, this will be temp.
So, assuming you have a default index configured and no convention for type names, the request URI for your NEST example will be
<configured uri>/<default index>/temp/_search
which probably does not match what you are using in Postman.
Check out the documentation to see more details about Index name inference and Type name inference.

How to remove table names in JDBC response in SOAPUI

In SOAPUI tool, in response for any DB step, response contains with tableName.column.
please refer the below image.
How can remove the tableName attribute from the response.
I mean to ask, is there any setting in SOAPUI or is there any properties file I need to update...
This doesn't depends on settings from SOAPUI, it's depends on DB drivers.
I follow the SOAPUI code from github, and I finally found that internally JDBCTestSteps constructs the XML node names from response based on the follow code fragment:
...
public static Document addResultSetXmlPart(Element resultsElement, ResultSet rs, Document xmlDocumentResult)
throws SQLException {
ResultSetMetaData rsmd = rs.getMetaData();
...
...
String columnName = "";
if (!StringUtils.isNullOrEmpty(rsmd.getTableName(ii))) {
columnName += (rsmd.getTableName(ii)).toUpperCase() + ".";
}
columnName += (rsmd.getColumnName(ii)).toUpperCase();
String value = rs.getString(ii);
Element node = xmlDocumentResult.createElement(StringUtils.createXmlName(columnName));
...
(You can see the whole method addResultSetXmlPart method form XMLUtils class here)
So as you can see the node name on the XML depends on ResultSetMetaData getTableName and getColumnName methods. This class is an interface and the implementation of these methods depends on specific DB driver version.
So to have the same behavior as your client, simply check that both have the same DB drivers in SOAPUI_HOME\bin\ext.
REMARK: Once you or your client change the .jar in SOAPUI_HOME\bin\ext restart SOAPUI in order to load the new ones.
Hope this helps,
"postgresql-9.1-903.jdbc4" should return the resultset without the table names. I got it working without placing the db driver to the SOAPUI_HOME\bin\ext.

How to execute RemoveAliasMapping in ElasticSearch using JEST

I am trying to remove an alias mapping for an index in ES using jest.
Here is what I have tried :
// create Jest Client.
JestClient client = factory.getObject();
// create RemoveAliasMapping Object.
RemoveAliasMapping removeAliasMapping = new RemoveAliasMapping.Builder("oldIndex", "alias").build();
After creating the removeAliasMapping object, I couldn't find a way to execute it.
If I use the api : client.execute(removeAliasMapping), it says : The method execute(Action<T>) in the type JestClient is not applicable for the arguments (RemoveAliasMapping)
Also, I couldn't find any other api exposed to execute AliasMapping.
Can anyone help me out with this here? If possible, please put an example too.
Try this:
ModifyAliases modifyAliases = new ModifyAliases.Builder(new RemoveAliasMapping.Builder("oldIndex", "alias").build()).build();
JestResult result = client.execute(modifyAliases);

Issue Retrieving a Screenshot from a database

I've got a bunch of screenshots and some screenshot meta data I'm trying to display in an ASP.NET MVC 3 web application, I'm trying to retrieve the data from my databse but I get this error:
LINQ to Entities does not recognize the method 'System.Drawing.Image
ByteArrayToImage(Byte[])' method, and this method cannot be translated
into a store expression.
Here's my code:
var screenshotData = (from screenshots in db.screenshots
where screenshots.projects_ID == projectID
select new ImageInformation
{
ID = screenshots.id,
Language = screenshots.language,
Screenshot = Utility.ByteArrayToImage(screenshots.screen_shot),
ProjectID = screenshots.projects_ID
});
foreach (ImageInformation info in screenshotData)
{
this.Add(info);
}
ImageInformation is just a simple class that contains the defintion the information stored (ID, Language, Screenshot, ProjectID).
Here's my ByteArrayToImage function:
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
Can anybody tell me why I receive this error when this code runs?
Thanks.
I think it's because, with LINQ-to-Entities, the code is turned into server-side query and it can't do that in this case. I don't think you can mix client-side code like this directly with L2E.
I would suspect you will have to do the conversion from byte->image after you've retrieved the data from the database as a distinct step.
You can't do the function in a LINQ to Entities query... one option:
1) have a byte[] property on the object you are instantiating (ImageInformation) and copy the data in there along with another propery to read the image from this ImageInformation object.

Resources