Datanucleus JDO setting fields to null - mysql

In an attempt to find another issue, my tests came up with the following bit of code.
public class TestPersistance {
private static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");
public static final PersistenceManager pm = PMF.getPersistenceManager();
static final TestUserDataDB ud = new TestUserDataDB();
public static void main(String args[])
{
TestPersistance tp = new TestPersistance();
tp.createData();
}
#Test public void createData()
{
assertTrue("Null machined id at start", ud.machineId != null);
pm.currentTransaction().begin();
try
{
pm.makePersistent(ud);
}
finally
{
pm.currentTransaction().commit();
}
assertTrue("Null machined id at end", ud.machineId != null);
}
}
where the second assert fails. ie. my object that I am asking to be persisted is being changed by the makePersistent call. The data is being stored in the database.
Any ideas? Can any one confirm this.
using
jdo-api-3.0.jar
datanucleus-core-2.2.0-release.jar
datanucleus-enhancer-2.1.3.jar
datanucleus-rdbms-2.2.0-release.jar
mysql-connector-java-5.1.13.jar
in eclipse with MySql database.
#PersistenceCapable
public class TestUserDataDB {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
public Long id;
#Persistent
public String userid = "test1";
#Persistent
public String machineId = "test2";
// local userid
#Persistent
public long uid = 1L;
#Persistent
public long systemTime = 123L;
public long chk = 1234L;
public long createTime = System.currentTimeMillis();
public TestUserDataDB()
{
}
#Override
public String toString() {
return "TestUserDataDB [chk=" + chk + ", createTime=" + createTime
+ ", id=" + id + ", machineId=" + machineId + ", systemTime="
+ systemTime + ", uid=" + uid + ", userid=" + userid + "]";
}
}
Properties file is
javax.jdo.PersistenceManagerFactoryClass=org.datanucleus.jdo.JDOPersistenceManagerFactory
datanucleus.metadata.validate=false
javax.jdo.option.ConnectionDriverName=com.mysql.jdbc.Driver
javax.jdo.option.ConnectionURL=jdbc:mysql://localhost/test
javax.jdo.option.ConnectionUserName=root
javax.jdo.option.ConnectionPassword=yeahRight
datanucleus.autoCreateSchema=true
datanucleus.validateTables=false
datanucleus.validateConstraints=false

Why are you accessing fields directly ? Is the accessing class declared as PersistenceAware ? Well it isn't so you can't do that - use the getters.
What is "ud" object state before persist ? (transient?) what is it after persist ? (hollow?) What does the log say ? Chances are that it is in hollow state and then you access a field directly and it has no value (by definition, as per the spec) ... but since you didn't bother calling the getter it hasn't a chance to retrieve the value. And you likely also don't have "RetainValues" persistent property set
Suggest you familiarise yourself with the JDO spec and object lifecycle states

In some cases, it is necessary to access deserialized objects' attributes directly (i.e. if using GSON library for JSON serialization). In that case you can use:
MyClass copy = myPersistencyManager.detachCopy(myRetrievedInstance);

Related

Get data array from sqlite database and post to API via json object... can be possible?

newbie here... i was developing app that send my data to api via retrofit. my code was working but it sends 1 data input only at the time.... in my case, i've like to do is I want to get more saved data in my sqlite (example 5 data saved) and send it all on api via json object.
This is my Activity:
DatabaseHelper databaseHelper2 = new
DatabaseHelper(getApplicationContext());
SQLiteDatabase db2 =
databaseHelper2.getWritableDatabase();
Cursor cursor =
databaseHelper2.retrieveSettingFromLocalDatabase(db2);
while (cursor.moveToNext()) {
ADDRESS =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL=cursor.getString
(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
}
portInts=Integer.parseInt(PORT);
MapDetails mapDetails = new MapDetails(gg, lat, lon,
well, "0", portInts); //Datas ive get to send in api
List<MapDetails> data = new ArrayList<>();
data.add(mapDetails);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://" + ADDRESS + ":" + PORT)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Api locate = retrofit.create(Api.class);
Call<MapDetails> call = locate.mapDetailLocation(data);
call.enqueue(new Callback<MapDetails>() {
#Override
public void onResponse(Call<MapDetails> call, Response<MapDetails> response) {
Snackbar.make(view, "" + response,
Snackbar.LENGTH_INDEFINITE)
.setAction("Action", null).show();
}
#Override
public void onFailure(Call call, Throwable t) {
Snackbar.make(view, "" + t.getMessage(),
Snackbar.LENGTH_INDEFINITE)
.setAction("Action", null).show();
}
});
This is my code in API:
public interface Api {
#POST("/api/Database/NewLocation")
Call<MapDetails> mapDetailLocation(#Body List<MapDetails> mapDetails)
}
This is my sample Client:
public class MapDetails {
#SerializedName("SerialNumber")
#Expose
private String SerialNumber;
#SerializedName("Coordinate1")
#Expose
private String Coordinate1;
#SerializedName("Coordinate2")
#Expose
private String Coordinate2;
#SerializedName("DateTime")
#Expose
private String DateTime;
#SerializedName("Speed")
#Expose
private String Speed;
#SerializedName("Port")
#Expose
private int Port;
public MapDetails(String serialNumber, String coordinate1, String
coordinate2, String dateTime, String speed, int port) {
SerialNumber = serialNumber;
Coordinate1 = coordinate1;
Coordinate2 = coordinate2;
DateTime = dateTime;
Speed = speed;
Port = port;
}
public String getSerialNumber() {
return SerialNumber;
}
public void setSerialNumber(String serialNumber) {
SerialNumber = serialNumber;
}
public String getCoordinate1() {
return Coordinate1;
}
public void setCoordinate1(String coordinate1) {
Coordinate1 = coordinate1;
}
public String getCoordinate2() {
return Coordinate2;
}
public void setCoordinate2(String coordinate2) {
Coordinate2 = coordinate2;
}
public String getDateTime() {
return DateTime;
}
public void setDateTime(String dateTime) {
DateTime = dateTime;
}
public String getSpeed() {
return Speed;
}
public void setSpeed(String speed) {
Speed = speed;
}
public int getPort() {
return Port;
}
public void setPort(int port) {
Port = port;
}
}
this is my sqlite database ive like to retrieve:
this is the sample posting ive created at the top
but in my case, ive like to do is this one, getting the saved data from my database and send it like this,:
The reason why only one is being sent is that you are sending outside of the while loop that traverses the Cursor, so only the last is sent.
That is you have :-
while (cursor.moveToNext()) {
ADDRESS = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
}
So say the query extracted a Cursor with 10 rows as address 1,2,3....10 (for explantory purposes) then
The loop is entered ADDRESS is set to 1, the next iteration sets it to 2, the next to 3 ..... and finally ADDRESS is set to 10 (same for PORT and TIMEINTERVAL)
After the loop the data is sent so only one is sent (ADDRESS 10).
What you need is along the lines of :-
List<MapDetails> data = new ArrayList<>();
MapDetails mapDetails
Retrofit.Builder builder;
Retrofit retrofit;
Call<MapDetails> call;
Api locate;
while (cursor.moveToNext()) {
ADDRESS = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
portInts=Integer.parseInt(PORT);
mapDetails = new MapDetails(gg, lat, lon, well, "0", portInts);
data.clear(); //<<<<<<<< remove previous entries if required????
data.add(mapDetails);
builder = new Retrofit.Builder()
.baseUrl("http://" + ADDRESS + ":" + PORT)
.addConverterFactory(GsonConverterFactory.create());
retrofit = builder.build();
locate = retrofit.create(Api.class);
call = locate.mapDetailLocation(data);
call.enqueue(new Callback<MapDetails>() {
#Override
public void onResponse(Call<MapDetails> call, Response<MapDetails> response) {
Snackbar.make(view, "" + response,
Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
#Override
public void onFailure(Call call, Throwable t) {
Snackbar.make(view, "" + t.getMessage(),
Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
}
Note the above is in-principle code. it has not been checked or tested and may therefore contain some errors.
It may be that you can send an entire set e.g. data with populated in which case you may only need up to data.add(mapDetails); in the loop and then have the following code outside the loop.
If I understood your question properly, you need to send JSONArray as payload for the request. But, you made a little mistake while preparing payload from SQLite database. #Mike T pointed out that mistake in his answer to your question.
Follow these codes to fix the problem.
DatabaseHelper databaseHelper2 = new DatabaseHelper(getApplicationContext());
SQLiteDatabase db2 = databaseHelper2.getWritableDatabase();
Cursor cursor = databaseHelper2.retrieveSettingFromLocalDatabase(db2);
List<MapDetails> data = new ArrayList<>(); // declare ArrayList outside and before while loop
while (cursor.moveToNext()) {
ADDRESS = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_ADDRESS));
PORT = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_PORT));
TIMEINTERVAL = cursor.getString(cursor.getColumnIndex(DatabaseHelper.SETTING_TIME_INTERVAL));
// pass arguments to MapDetails class constructor
portInts = Integer.parseInt(PORT);
MapDetails mapDetails = new MapDetails(gg, lat, lon, well, "0", portInts); //Datas ive get to send in api
// add prepared data to ArrayList
data.add(mapDetails);
}
// and finally execute network call
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("http://" + ADDRESS + ":" + PORT)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
Api locate = retrofit.create(Api.class);
Call<MapDetails> call = locate.mapDetailLocation(data);
call.enqueue(new Callback<MapDetails>() {
#Override
public void onResponse(Call<MapDetails> call, Response<MapDetails> response) {
Snackbar.make(view, "" + response, Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
#Override
public void onFailure(Call call, Throwable t) {
Snackbar.make(view, "" + t.getMessage(), Snackbar.LENGTH_INDEFINITE).setAction("Action", null).show();
}
});
PS: I'm not sure why are you taking ADDRESS and PORT from SQLite database. If they're same in every single row you don't need to take it from database right?

_class property in CouchBase

I have a document stored in Couchbase.
{
"a": {
"b": {
"key":"Value"
},
"_class":"com.nikhil.model"
},
"c":{
"d":{
"key":"value"
},
// _class is missing here
},
"_class": "com.nikhil.model"
}
Here as you can see I don't have an _class inside the "d" in the doucument because of this I am not able to get this document. An object mapping exception came.
_class is used to map the nested object of couchbase to the model required for mapping but inside the "c" object I don't have this _Class property that is why a mapping exception comes.
Is there any fix for this?
If you are using Spring boot, you need to override the typekey() method in the Couchbase Config file which extends AbstractCouchbaseConfiguration and return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE. This will replace your _class with javaClass string in the documents stored in Couchbase Server. I hope this helps.
#Configuration
public class RemoteCouchbaseConfiguration extends AbstractCouchbaseConfiguration {
#Value("${couchbase.host}")
private String host;
#Value("${couchbase.bucket.bucketName}")
private String bucketName;
#Value("${couchbase.bucket.password}")
private String password;
#Override
protected List<String> getBootstrapHosts() {
return Arrays.asList(this.host);
}
#Override
protected String getBucketName() {
return this.bucketName;
}
#Override
protected String getBucketPassword() {
return this.password;
}
#Override
public String typeKey() {
return MappingCouchbaseConverter.TYPEKEY_SYNCGATEWAY_COMPATIBLE;
}
}
Looks like you are using Couchbase with Spring Data, the easiest way is to return a projection:
#Override
public List<UserVO> getUsers(String companyId, List<String> userIds) {
String queryString = "SELECT meta(t).id as id, t.login as login, t.firstName as firstName from " + getBucketName() + " t where t."+getClassFilter()+" "
+ " and t.companyId = '" + companyId + "' and t.isEnabled = true and t.isVisible = true "
+ " and meta(t).id in ["+userIds.stream().map(e->"'"+e+"'").collect( Collectors.joining( "," )) +"]";
N1qlParams params = N1qlParams.build().consistency(ScanConsistency.NOT_BOUNDED).adhoc(true);
ParameterizedN1qlQuery query = N1qlQuery.parameterized(queryString, JsonObject.create(), params);
return userRepository.getCouchbaseOperations().findByN1QLProjection(query, UserVO.class);
}
You could add _class to it using an UPDATE N1QL statement like this:
UPDATE mybucket b
SET b.c.d._class = 'com.foo.bar'
WHERE b.c.d IS NOT MISSING
AND b.c.d._class IS MISSING
That will update any document that has a 'd' object within a 'c' object but doesn't have a '_class' within the c object.

ConfirmBehavior dosen't support Ajax rendreing

After an Ajax update of a button with a ConfirmBehavior, all Confirm dialog attributes (Header, Message, Icon) becomes Null.
Its look like thoses values are evaluated during the buildView phase only (applyMetadata function)
In the getHeader()/getMessage()/getIcon() methods of the ConfirmBehavior there is no evaluation of expression.
How to get the real expression at this point ? (to evaluate it during the render phase)
Not a perfect solution
public class ConfirmBehavior extends ClientBehaviorBase {
private String header;
private String message;
private String icon;
#Override
public String getScript(ClientBehaviorContext behaviorContext) {
FacesContext context = behaviorContext.getFacesContext();
UIComponent component = behaviorContext.getComponent();
String source = component.getClientId(context);
if(component instanceof Confirmable) {
String headerExpr = (String) component.getAttributes().get("confirm_header");
if (headerExpr!=null)
this.header = (String) ContextUtil.eval(context, headerExpr);
String messageExpr = (String) component.getAttributes().get("confirm_message");
if (messageExpr!=null)
this.message = (String) ContextUtil.eval(context, messageExpr);
String iconExpr = (String) component.getAttributes().get("confirm_icon");
if (iconExpr!=null)
this.icon = (String) ContextUtil.eval(context, iconExpr);
String script = "PrimeFaces.confirm({source:'" + source + "',header:'" + getHeader() + "',message:'" + getMessage() + "',icon:'" + getIcon() + "'});return false;";
((Confirmable) component).setConfirmationScript(script);
return null;
}
else {
throw new FacesException("Component " + source + " is not a Confirmable. ConfirmBehavior can only be attached to components that implement org.primefaces.component.api.Confirmable interface");
}
}
...
}

Not getting expected missing property/method exception testing Groovy class

While putting together a presentation, I have a situation in which I expect an exception, but I am getting none, when I run my corresponding unit test. What I am doing is incrementally modifying a bean. In this version of the Product and Accessory classes, I have removed the setters/getters for all the properties (save for a setter for one of the Product properties). I have previously converted my classes to use field access notation. So, since I have removed the setters/getters, I am expecting an exception because the field visibility modifiers are private.
Here is the Accessory class:
public class Accessory {
private String name
private BigDecimal cost
private BigDecimal price
public Accessory() {
this.cost = BigDecimal.ZERO
this.price = BigDecimal.ZERO
}
public Accessory(String name, BigDecimal cost, BigDecimal price) {
this.name = name
this.cost = cost
this.price = price
}
#Override
public int hashCode() {
final int prime = 31
int result = 1
result = prime * result + ((cost == null) ? 0 : cost.hashCode())
result = prime * result + ((name == null) ? 0 : name.hashCode())
result = prime * result + ((price == null) ? 0 : price.hashCode())
return result
}
public boolean equals(Accessory obj) {
return name == obj.name &&
cost == obj.cost &&
price == obj.price
}
#Override
public String toString() {
return "Accessory [" + "name=" + name + ", cost=" + cost + ", price=" + price + "]"
}
}
Here are snippets from the Product class:
public class Product {
private String model
private List<Accessory> accessories
private TreeMap<Integer, BigDecimal> priceBreaks
private BigDecimal cost
private BigDecimal price
...
public BigDecimal getAccessorizedCost() {
...
for (Accessory pkg : this.accessories) {
pkgCost = pkgCost.add pkg.cost
}
return pkgCost
}
...
}
I would expect that the line pkgCost = pkgCost.add pkg.cost in the above snippet would throw an exception. Likewise, I would think the following asserts in my unit test would do the same:
#Test public void canCreateDefaultInstance() {
assertNull "Default construction of class ${defaultProduct.class.name} failed to properly initialize model.", defaultProduct.model
assertTrue "Default construction of class ${defaultProduct.class.name} failed to properly initialize accessories.", defaultProduct.accessories.isEmpty()
assertTrue "Default construction of class ${defaultProduct.class.name} failed to properly initialize priceBreaks.", defaultProduct.priceBreaks.isEmpty()
assertEquals "Default construction of class ${defaultProduct.class.name} failed to properly initialize cost.", BigDecimal.ZERO, defaultProduct.cost as BigDecimal
assertEquals "Default construction of class ${defaultProduct.class.name} failed to properly initialize price.", BigDecimal.ZERO, defaultProduct.price as BigDecimal
}
Here are the metaclass properties and methods:
MetaClass Properties are:
[accessorizedCost, accessorizedPrice, class, priceBreaks]
MetaClass Methods are:
[__$swapInit, addPriceBreak, calcDiscountMultiplierFor, calcVolumePriceFor, equals, getAccessorizedCost, getAccessorizedPrice, getClass, getMetaClass, getProperty, hashCode, invokeMethod, notify, notifyAll, setMetaClass, setPriceBreaks, setProperty, toString, wait]
You can see, for example, that there are no properties nor corresponding getter/setters for the privately defined model, accessories, cost and price fields. So, like the line in the Product class not failing when referencing the cost property of Accessory, I do not understand how the unit tests can pass when there is not property nor getter/setters for these private fields.
I am compiling using Groovy 2.0.4 and running Eclipse.
What am I missing or not understanding?

JPA difference Windows / Unix System?

For development purposes i'm using a windows environment (Eclipse / Jboss)
There i have a userDAO, that offers the method to rerieve a UserEntity by first- and lastname. This Query runs well on the dev environment. However on the Unix-Environment, i get a javax.persistence.NoResultException: No entity found for query Exception.
Situation in Detail:
A REST-Service is beeing called, containing many Data, along with a firstname and lastname. this parameters needs to be used to obtain the actuall userEntity. (It fails for ANY user on Unix.)
So, the rest service is doing this:
#Consumes("application/json")
#Produces("application/json")
public String create(String plaindata) {
JSONObject data = new JSONObject(plaindata);
String ownerFirstname = data.getString("userFirstname"); //Yes userX, not ownerX
String ownerLastname = data.getString("userLastname");
UserEntity owner = null;
try {
owner = userDataService.getUserDetailsByName(ownerFirstname, ownerLastname);
} catch (Exception e) {
throw new Exception("Found zero possible users for the given name '" + ownerFirstname + " " + ownerLastname
+ "'. Cannot invoke process.", e);
}
...
}
The userDataService looks (stripped) like this:
private static String GET_USER_BY_FIRSTNAME_LASTNAME_QUERY = "SELECT * FROM " + DBConstants.USER_TABLE_NAME
+ " user WHERE user.FIRST_NAME = :firstnameValue AND user.LAST_NAME = :lastnameValue";
public UserEntity getUserDetailsByName(String firstname, String lastname) {
Query query = em.createNativeQuery(GET_USER_BY_FIRSTNAME_LASTNAME_QUERY, UserEntity.class);
query.setParameter("firstnameValue", firstname);
query.setParameter("lastnameValue", lastname);
UserEntity u = (UserEntity) query.getSingleResult();
return u;
}
DBConstants contains the table name like:
public static final String DATATABLE_PREFIX = "pre_";
public static final String USER_TABLE_NAME = DATATABLE_PREFIX+"user_entity";
Column Names in mySQL are Capitalized, so everything seems right.
this works on a Windows Environment, but NOT in the Unix Environment :(
String ownerFirstname = data.getString("userFirstname").trim();
String ownerLastname = data.getString("userLastname").trim();
And it works... Strange thing - what could be the difference between windows and unix towards this issue? (The Exception logged absolutely NO Whitespace)