Broadleaf - Create Dynamic Product Exception - java

I am new to Broadleaf and have been spending time with Broadleaf Demo project to familiarize with the framework.
I am using the current stable Broadleaf version - v2.2.
My aim is to create a dynamic category/product without using the Admin console. However, I am getting TransientObjectException:
java.lang.IllegalStateException: org.hibernate.TransientObjectException: object is an unsaved transient instance - save the transient instance before merging: org.broadleafcommerce.core.catalog.domain.CategoryImpl
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1386)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1317)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1323)
This is how I am trying to create category/product:
private void addProductMetaData(Product product) {
product.setName("phone A");
product.setFeaturedProduct(true);
product.setUrl("/phones/phoneA");
product.setCanSellWithoutOptions(true);
product.setManufacturer("manufacturer A");
product.setActiveStartDate(new Date());
product.setActiveEndDate(null);
addMediaInformation(product);
Category category = retrieveCategory();
product.setDefaultCategory(category);
// product.getAllParentCategories().add(category);
catalogService.saveProduct(product); //**Exception occurs here**
}
private Category retrieveCategory() {
List<Category> categories = catalogService.findCategoriesByName("phones");
Category category = (CollectionUtils.isEmpty(categories) ? catalogService.createCategory() : categories.get(0));
if (StringUtils.isEmpty(category.getName())) {
category.setName("phones");
category.setUrl("/phones");
Category parentCategory = catalogService.findCategoriesByName("Primary Nav").get(0);
category.setDefaultParentCategory(parentCategory);
category.setActiveStartDate(new Date());
category.getAllParentCategories().add(parentCategory);
catalogService.saveCategory(category);
}
return category;
}
Can someone explain why I am getting this exception( since category has been persisted) and how do I resolve it?

Looks to me like catagories list is empty, resulting in a call to service that fetches you new Category. Now, though you are associated this new category with product, but this new category is not saved in database.
You need to persist this new category first and than call save on product. This should resolve the issue.
And if this category is persisted than somehow hibernate is not able match this category with the one that you think is persisted.

I figured out the fix. Modified the line : catalogService.saveCategory(category);
to category = catalogService.saveCategory(category); and I am no longer getting the exception.

Related

How to get RTC work item attribute data using java API?

I am using below code and it returns some information about "Filed Against"
attribute. But there I am not able to find attribute data. Please help
IAttribute someAttribute= workItemClient.findAttribute(projectAreaHandle, workItem.CATEGORY_PROPERTY, monitor);
Using below code to find out the work item by Id :
workItemClient = (IWorkItemClient) repo.getClientLibrary(IWorkItemClient.class);
int id = new Integer("339406").intValue();
IWorkItem workItem = workItemClient.findWorkItemById(id, IWorkItem.FULL_PROFILE, monitor);
using this work item I want to fetch parent and children like Epic and story work items related to the work item. And then there attributes like story status, story planned for etc.
From this thread:
You can't just put a string in there, I think.
You have to find the category object from the string and then put in the ICategory object.
That means:
private static String CATEGORY_NAME = "UI1";
List<ICategory> findCategories = workItemCommon.findCategories(projectArea, ICategory.FULL_PROFILE, monitor);
for(ICategory category : findCategories) {
if(category.getName().contains(CATEGORY_NAME)){
filedAgainstAttribute = QueryableAttributes.getFactory(IWorkItem.ITEM_TYPE).findAttribute(projectArea, IWorkItem.CATEGORY_PROPERTY, auditableClient, monitor);
filedAgainstExpression = new AttributeExpression(filedAgainstAttribute, AttributeOperation.EQUALS, category);
}
}

Create BE Initiative, BE Feature and CPM Feature using Rally Rest Client in Java

We are trying to automate the project migration from one Rally workspace to other. Everything seems to work fine like we are able to migrate project and related releases/iterations/userstories/tasks from one workspace to another workspace.
But while trying to migrate BE Initiative/BE Feature/CPM Feature we are getting some exception related to Null Pointer exception but the error we are getting in Response doesn't seem to give much info.
A sample of code is -
String oldProjectObjectId = "12345";
String newProjectObjectId = "67890";
String oldRallyWorkspaceObjectId = "32145";
String newRallyWorkspaceObjectId = "67894";
QueryResponse beInitiativeResponse = queryRally("portfolioitem/beinitiative", "/project/"+this.oldProjectObjectId, "/workspace/"+this.oldRallyWorkspaceObjectId);
int beInitiativeCount = beInitiativeResponse.getTotalResultCount();
if(beInitiativeCount >0){
JsonArray initiativeArray = beInitiativeResponse.getResults();
for(int i=0; i< initiativeArray.size();i++){
JsonObject beInitiativeObject = initiativeArray.get(i).getAsJsonObject();
String oldBeInitiativeObjectId = beInitiativeObject.get("ObjectID").getAsString();
String oldBeInitiativeName = beInitiativeObject.get("_refObjectName").getAsString();
String owner = getObjectId(beInitiativeObject, "Owner");
JsonObject BeInitiativeCreateObject = getJsonObject(oldBeInitiativeName, "/project/"+this.newProjectObjectId, "/workspace/"+this.newRallyWorkspaceObjectId, owner);
CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject);
if(beInitiativeCreateResponse.wasSuccessful()){
String newBeInitiativeObjectId = beInitiativeCreateResponse.getObject().get("ObjectID").getAsString();
String mapKey = oldBeInitiativeObjectId;
String mapValue= newBeInitiativeObjectId;
this.beInitiativesHashMap.put(mapKey, mapValue);
}
else{
String[] errorList;
errorList = beInitiativeCreateResponse.getErrors();
for (int j = 0; j < errorList.length; j++) {
System.out.println(errorList[j]);
}
}
}
}
queryRally and createInRally functions use Rally rest client to fetch and create the required projects and associated attributes like releases, iterations etc.
After executing CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/beinitiative", BeInitiativeCreateObject); when it's trying to execute if(beInitiativeCreateResponse.wasSuccessful()) it is instead going to else block and thus printing the below mentioned error.
An unexpected error has occurred.We have recorded this error and will begin to investigate it. In the meantime, if you would like to speak with our Support Team, please reference the information below:java.lang.NullPointerException2017-12-05 11:01 AM PST America/Los_Angeles
But the important point that is when trying to migrate projects and it's related attributes like release/iterations etc. withing same Rally workspace the above piece of code works just fine.
Update1:
While analysing the issue I made the following observations -
The workspace in which I am trying to create the BeInitiative doesn't have BEinitiative, Be Feature, CPM Feature options in Portfolio items dropdown. Rather it has Theme, Initiative and Feature options in it.
Therefore, I think I was getting the previouly mentioned error. Now I made the following changes to the code.
CreateResponse beInitiativeCreateResponse = createInRally("portfolioitem/theme", themeCreateObject);
So now instead of creating the BEInitiative I am trying to create the theme only in new workspace but getting the following error -
Requested type name \"/portfolioitem/theme\" is unknown.
The object that i am passing to CreateResponse function is -
{"Name":"xyz","Project":"/project/1804","Workspace":"/workspace/139"}
Also code for createInRally function is as mentioned below -
public CreateResponse createInRally( String query, JsonObject object) throws IOException{
CreateRequest createRequest = new CreateRequest(query, object);
CreateResponse createResponse = restApi.create(createRequest);
return createResponse;
}
The Unknown Type error was occurring as a result of not passing the workspace's object id in which we were trying to create the portfolio item.
So after modifying the createInRally function to include the workspace object id we were able to create the initiative portfolio item.
The modified createInRally function is as shown below-
CreateRequest createRequest = new CreateRequest(query, object);
createRequest.addParam("workspace", "/workspace/1333333333");
CreateResponse createResponse = restApi.create(createRequest);
return createResponse;
So this is definitely an error in the web services api. You should never get 500 responses with an unhandled nullpointer. My initial guess is that when you're creating your new object some field on it is still referencing an object in the old workspace, and when we try to correctly hook up all the associations it fails to read one of those objects in the new workspace. Can you provide some more information about what your actual object you're sending to create looks like? Specifically what object relationships are you including (that may not be valid in the new workspace)?

Why System.out.println() can solving my Hibernate Session?

Hello I'm newbie in learning hibernate framework. I was solved my error but I don't know what the problem happen. In my project I have 2 tables Tblbarang and Tbljenis. And 1 field at Tblbarang had relations as foreign key by Tbljenis.
I want to update Tblbarang table. I had two method
private void getcombobarang() {
Query q = sess.createQuery("from Tblbarang");
arrbarang = new ArrayList<>();
DefaultComboBoxModel comboModel = new DefaultComboBoxModel();
for (Object o : q.list()) {
Tblbarang coba = (Tblbarang) o;
comboModel.addElement(coba.getNamabarang());
arrbarang.add(coba);
}
combobarang.setModel(comboModel);
}
This method to set model combobox which I would choose to set the table Tblbarang item.
and now this method to update my Table Tblbarang
sess = NewHibernateUtil.getSessionFactory().openSession();
sess.beginTransaction();
Tblbarang tb = new Tblbarang();
tb.setKodbarang(arrbarang.get(combobarang.getSelectedIndex()).getKodbarang());
tb.setNamabarang(arrbarang.get(combobarang.getSelectedIndex()).getNamabarang());
tb.setTbljenis(arrbarang.get(combobarang.getSelectedIndex()).getTbljenis());
tb.setHarganet(arrbarang.get(combobarang.getSelectedIndex()).getHarganet());
tb.setHargajual(arrbarang.get(combobarang.getSelectedIndex()).getHargajual());
System.out.println(arrbarang.get(combobarang.getSelectedIndex()).getTbljenis()); // <-- this line resolved my problem
int st = Integer.parseInt(stok.getText()) ;
int jm = Integer.parseInt(jumlah.getText());
String totss = String.valueOf(st + jm);
Short totstok = Short.parseShort(totss);
tb.setStok(totstok);
sess.update(tb);
sess.getTransaction().commit();
when without System.out.print() the error are following
org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
at org.hibernate.proxy.AbstractLazyInitializer.setSession(AbstractLazyInitializer.java:126)
at org.hibernate.proxy.AbstractLazyInitializer.setSession(AbstractLazyInitializer.java:126)
at org.hibernate.engine.StatefulPersistenceContext.reassociateProxy(StatefulPersistenceContext.java:573)
at org.hibernate.engine.StatefulPersistenceContext.reassociateIfUninitializedProxy(StatefulPersistenceContext.java:533)
at org.hibernate.event.def.ProxyVisitor.processEntity(ProxyVisitor.java:50)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:125)
at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:83)
at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:77)
at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:144)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:314)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:246)
at org.hibernate.event.def.DefaultUpdateEventListener.performSaveOrUpdate(DefaultUpdateEventListener.java:57)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireUpdate(SessionImpl.java:742)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:730)
at org.hibernate.impl.SessionImpl.update(SessionImpl.java:722)
at retail.ui.frmBarangMasuk.tambahitemActionPerformed(frmBarangMasuk.java:622) //<-this line directing to sess.update(tb)
I will simply my code like this
sess = NewHibernateUtil.getSessionFactory().openSession();
sess.beginTransaction();
Tblbarang tb = (Tblbarang) arrbarang.get(combobarang.getSelectedIndex());
System.out.println(arrbarang.get(combobarang.getSelectedIndex()).getTbljenis());
int st = Integer.parseInt(stok.getText()) ;
int jm = Integer.parseInt(jumlah.getText());
String totss = String.valueOf(st + jm);
Short totstok = Short.parseShort(totss);
tb.setStok(totstok);
sess.update(tb);
sess.getTransaction().commit();
but the exception showing same error. I want to know what happen with my code? anyone can explain with that issue or this is bug from hibernate, thanks
In getcombobarang, you have a sess(session1) to get objects from database. And when updating tb, you open another sess(session2).
If Tblbarang contains a foreign-key object, in this case, which must associates with session1, because it's obtained from the function getcombobarang at first. So sess.update() throws an exception as you have seen.
For solution:
use merge() instead of update()
before update, copy the foreign-key object's properties to a whole new object, then set it into tb
I'm also confused about the impact of System.println() here.

Create Product in MS Dynamics CRM 2011 via SOAP/Java

I generated all required java classes from crm.dynamics.com/XRMServices/2011/Discovery.svc?wsdl and crm.dynamics.com/XRMServices/2011/Organization.svc?wsdl schemas.
I authenticated in CRM with LiveId.
Now i need to create Product in Product Catalog. Here is code for this:
Entity newEntryInfo = new Entity();
AttributeCollection collection = new AttributeCollection();
addAttribute(collection, "name", "Tama Starclassic Performer");
addAttribute(collection, "productnumber", "1");
addAttribute(collection, "price", createMoney("100.0"));
addAttribute(collection, "isstockitem", Boolean.TRUE);
addAttribute(collection, "statuscode", 1);
newEntryInfo.setAttributes(collection);
newEntryInfo.setLogicalName("product");
Guid productGuid = serviceStub.create(newEntryInfo);
private void addAttribute(AttributeCollection collection, String key, Object value) {
KeyValuePairOfstringanyType values = new KeyValuePairOfstringanyType();
values.setKey(key);
values.setValue(value);
collection.addKeyValuePairOfstringanyType(values);
}
Execution shows error "The unit schedule id is missing."
Looks like i need to provide "Unit Group" and "Default Unit" for new product.
Question: How can i set those values? Should i use RelatedEntities (how create it) or Attributes (how create it)
As it is a lookup on the form, you should be able to set the value with an EntityReference.
Using your methods that would be:
addAttribute(collection, "fieldName", new EntityReference("entityName", new Guid("id"))
Where:
fieldName is the schema name of the field you want to populate
entityName is the schema name of the entity you want to populate the field with
id is the Guid of a record which is the same type as entityName.
To put that into a context (where I happen to know the schema names off the top of my head).
//Create a new contact first
Entity contact = new Entity("contact");
contact["lastname"] = "Wood";
Guid contactId = service.Create(contact);
//Create an incident/case which links to that new contact
Entity incident = new Entity("incident");
incident["customerid"] = new EntityReference("contact", contactId)
service.Create(incident)
As a side is there a particular reason you are using a such a long winded code style? The entity class has an index which links to underlying attribute dictionary. Its a bit more straight forward.
If you are looking for more examples check out: Use the Late Bound Entity Class in Code

Google App Engine - Deleted Entity is not deleted

I'm trying to delete an entity in google datastore
String keyValue = "someValue";
Key tweetKey = KeyFactory.createKey("tweetKey", keyValue);
Entity someEntity = new Entity(tweetKey);
Entity getEntity = datastore.get(tweetKey);
datastore.delete(tweetKey);
getEntity = datastore.get(tweetKey);
if(getEntity != null)
{
//This happens
System.out.println("Something wrong");
}
The entity are not deleted, and it something wrong as the output
Edit 1: I didn't copy and paste from the original code, because there are a lot of other logic in between getting and using values from the entity.
You are deleting a different key than the one you are checking.
You are deleting the tweetKey and checking the tweetkey (notice the capital K in the first one). If this snippet is a copy paste from your original then that's the mistake.
Make sure you don't have a transaction active and if you do commit it.

Categories