I want to make sure that an xml element-content is unmarshalled in upper case on my object.
public class SZM {
String field01;
#XmlElement(name="field01")
public void setField01(String value) {this.field01 = value.toUpperCase();}
public String getField01() {return field01;}
but how to do the same thing for every item in a collection? I want that any value read from the xml is capitalized.
#XmlElement
ArrayList<String>collection01;
Thanks in advance,
Agostino
all the class, just in case:
package test.jaxb;
import java.util.ArrayList;
import javax.xml.bind.annotation.*;
#XmlRootElement
public class SZM {
String field01;
#XmlElement(name="field01")
public void setField01(String value) {this.field01 = value.toUpperCase();}
public String getField01() {return field01;}
#XmlElement
ArrayList<String>collection01;
}
You can use an XmlAdapter to manipulate the String values:
StringCaseAdapter
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class StringCaseAdapter extends XmlAdapter<String, String> {
#Override
public String unmarshal(String v) throws Exception {
return v.toUpperCase();
}
#Override
public String marshal(String v) throws Exception {
return v.toLowerCase();
}
}
SZM
You reference the XmlAdapter as:
package test.jaxb;
import java.util.ArrayList;
import javax.xml.bind.annotation.*;
#XmlRootElement
public class SZM {
String field01;
#XmlElement(name="field01")
#XmlJavaTypeAdapter(StringCaseAdapter.class)
public void setField01(String value) {this.field01 = value;}
public String getField01() {return field01;}
#XmlElement
#XmlJavaTypeAdapter(StringCaseAdapter.class)
ArrayList<String>collection01;
}
input.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
<collection01>def</collection01>
<collection01>ghi</collection01>
<field01>abc</field01>
</szm>
Demo
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(SZM.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
SZM szm = (SZM) unmarshaller.unmarshal(new File("input.xml"));
System.out.println(szm.getField01());
for(String item : szm.collection01) {
System.out.println(item);
}
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(szm, System.out);
}
}
Output
ABC
DEF
GHI
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
<collection01>def</collection01>
<collection01>ghi</collection01>
<field01>abc</field01>
</szm>
Related
I want to store my data in realm but it is not working, it show me error when I click on save button where I add toast. There is no error found, but data is not saving.
My MainActivity Class
package com.deitel.realmrecyclerviewspinnerpriority;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.deitel.realmrecyclerviewspinnerpriority.Modelclass.ModelClass;
import io.realm.Realm;
public class MainActivity extends AppCompatActivity {
private static final String TAG="MainActivity";
Realm realm;
EditText text_name;
EditText text_details;
Button btn_save;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm=Realm.getDefaultInstance();
Realm.init(getApplicationContext());
text_name = findViewById(R.id.text_name);
text_details = findViewById(R.id.text_details);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
savedata(text_name.getText().toString(),text_details.getText().toString());
}
});
}
private void savedata(final String name, final String datails){
realm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm bgrealm) {
// Number maxid=bgrealm.where(ModelClass.class).max("id");
// int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
ModelClass user = bgrealm.createObject(ModelClass.class);
user.setName(name);
user.setDetails(datails);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
}
Realm Class Where I initilize configutation etc.
package com.deitel.realmrecyclerviewspinnerpriority;
import android.app.Application;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration configuration=new RealmConfiguration.Builder().name("RealmData.realm").build();
Realm.setDefaultConfiguration(configuration);
}
}
Model Class.
package com.deitel.realmrecyclerviewspinnerpriority.Modelclass;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class ModelClass extends RealmObject {
#PrimaryKey
private String Name;
private String Details;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDetails() {
return Details;
}
public void setDetails(String details) {
Details = details;
}
}
I think you are not setting primary key,
Try below approach
private void savedata(final String name, final String datails){
try(Realm mRealm = Realm.getDefaultInstance()){
ModelClass user = new ModelClass();
int newkey=(maxid==null) ? 1 : maxid.intValue()+1;
user.setId(newkey);
user.setName(name);
user.setDetails(datails);
mRealm.executeTransaction(rlm-> {
rlm.insertOrUpdate(user);
});
}
}
insertOrUpdate inserts a new record if PK doesn't exists else update it.
I'm trying to marshal and unmarshal Map to/from value pairs. I can marshal the object successfully, however, I cannot unmarshal it from the xml. The unmarshal result is the key exist in the Map, however, its value is null.
Here's the model I want to marshal and unmarshal:
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement(name="TestModel")
#XmlAccessorType(XmlAccessType.FIELD)
public class TestModel {
#XmlElement(name="Name")
private String name;
#XmlJavaTypeAdapter(MapAdapter.class)
private Map<String, String> metadata;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, String> metadata) {
this.metadata = metadata;
}
}
I create a Map Adapter for marshal and unmarshal like below:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.namespace.QName;
import org.w3c.dom.Element;
public class MapAdapter extends XmlAdapter<MapWrapper, Map<String, String>> {
#Override
public MapWrapper marshal(Map<String, String> m) throws Exception {
MapWrapper wrapper = new MapWrapper();
List<JAXBElement<String>> elements = new ArrayList<JAXBElement<String>>();
if (m != null && !m.isEmpty()) {
for (Entry<String, String> property : m.entrySet()) {
elements.add(new JAXBElement<String>(new QName(property.getKey()),
String.class, property.getValue().toString()));
}
}
wrapper.elements = elements;
return wrapper;
}
#Override
public Map<String, String> unmarshal(MapWrapper v) throws Exception {
Map<String, String> map = new HashMap<String, String>();
if (v != null && v.elements != null && !v.elements.isEmpty()) {
for (Object object : v.elements) {
Element element = (Element) object;
map.put(element.getNodeName(), element.getNodeValue());
}
}
return map;
}
}
class MapWrapper {
#XmlAnyElement(lax=true)
protected List<JAXBElement<String>> elements;
}
And the below class can test the marshal and unmarshal of the above model:
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class TestEntry {
public static void main(String[] args) throws JAXBException {
testMarshal();
testUnmarshal();
}
public static void testMarshal() throws JAXBException {
Map<String, String> metadata = new HashMap<String, String>();
metadata.put("category", "test");
metadata.put("creation", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
TestModel model = new TestModel();
model.setMetadata(metadata);
model.setName("TESTMODEL");
marshal(model, System.out);
}
public static void testUnmarshal() throws JAXBException {
String model = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"
+ "<TestModel>"
+ "<Name>TESTMODEL</Name>"
+ "<metadata>"
+ "<category>test</category>"
+ "<creation>2015-09-29</creation>"
+ "</metadata>"
+ "</TestModel>";
TestModel result = unmarshal(new ByteArrayInputStream(model.getBytes()), TestModel.class);
System.out.println("name=" + result.getName());
for (String key : result.getMetadata().keySet()) {
System.out.println(key + ", " + result.getMetadata().get(key));
}
}
public static <T> void marshal(T cls, OutputStream os) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(cls.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(cls, os);
}
#SuppressWarnings("unchecked")
public static <T> T unmarshal(InputStream is, Class<T> cls)
throws JAXBException {
JAXBContext context = JAXBContext.newInstance(cls);
Unmarshaller unmarshaller = context.createUnmarshaller();
return (T) unmarshaller.unmarshal(is);
}
}
It seems that, the map only contains the key with 'null' value when invoke 'public Map unmarshal(MapWrapper v) throws Exception'.
And I also find a similar question about this issue "JAXB: how to marshall map into <key>value</key>", however, it didn't solve the unmarshal issue?
A very small correction:
map.put(element.getNodeName(), element.getTextContent());
I'm trying to use this to select a value from a Custom Combo Box:
import java.util.List;
import javafx.application.Application;
import static javafx.application.Application.launch;
import static javafx.application.Application.launch;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class MainApp extends Application
{
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage)
{
final ComboBox<ListGroupsObj> listGroups = new ComboBox();
listGroups.setButtonCell(new GroupListCell());
listGroups.setCellFactory(new Callback<ListView<ListGroupsObj>, ListCell<ListGroupsObj>>()
{
#Override
public ListCell<ListGroupsObj> call(ListView<ListGroupsObj> p)
{
return new GroupListCell();
}
});
listGroups.setEditable(true);
listGroups.setConverter..............
// Insert Some data
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Test");
listGroups.getItems().addAll(ob);
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Test2");
listGroups.getItems().addAll(osb);
listGroups.setValue(ob);
// Display the selected Group
listGroups.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<ListGroupsObj>()
{
#Override
public void changed(ObservableValue<? extends ListGroupsObj> arg0, ListGroupsObj arg1, ListGroupsObj arg2)
{
if (arg2 != null)
{
System.out.println("Selected Group: " + arg1.getGroupId() + " - " + arg2.getGroupName());
}
}
});
final StackPane layout = new StackPane();
layout.getChildren().add(listGroups);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
}
class GroupListCell extends ListCell<ListGroupsObj>
{
#Override
protected void updateItem(ListGroupsObj item, boolean empty)
{
super.updateItem(item, empty);
if (item != null)
{
setText(item.getGroupId() + " - " + item.getGroupName());
}
}
}
private List<ListGroupsObj> listGroups;
public static class ListGroupsObj
{
private int groupId;
private String groupName;
public static ListGroupsObj newInstance()
{
return new ListGroupsObj();
}
public ListGroupsObj()
{
}
public ListGroupsObj groupId(int groupId)
{
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName)
{
this.groupName = groupName;
return this;
}
public int getGroupId()
{
return groupId;
}
public String getGroupName()
{
return groupName;
}
#Override
public String toString()
{
return groupId + " - " + groupName;
}
}
public class GroupConverter extends StringConverter<ListGroupsObj>
{
#Override
public String toString(ListGroupsObj obj)
{
return obj.getGroupId() + " - " + obj.getGroupName();
}
#Override
public ListGroupsObj fromString(String obj)
{
//TODO when you type for example "45 - NextGroup" you want to take only tyhe number"
return ListGroupsObj.newInstance().groupName(obj);
}
}
}
I get this error when I click outside of the comboBox:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: java.lang.String cannot be cast to com.selectmenuexample.MainApp$ListGroupsObj
I found that this can be done using convertor but I'm now aware how to use it. Can you help with this implementation?
Here is what is wrong:
You called your ComboBox listGroups and your List of Items listGroups. So in your start code, you were hiding that variable. So I removed that useless variable since you can manipulate Items directly in the ComboBox.
You had basically three methods/variable doing the exact same things. Converting your Object into a String with a "-" between them. So I removed the GroupConverter and the custom cellFactory. You don't need them because you already have your "toString()" method in your ListGroupsObj which is doing the job.
Then you misunderstood how the ComboBox is working. If it's editable, the ComboBox will allow something to be typed inside the TextField. That's where the StringConverter comes. It will allow you to make the conversion between a String and your ListGroupsObj and the way around.
In order to go from a ListGroupsObj to a String, simply call the "toString()" method on your object.
But in the way around, you should either create a new ListGroupsObj, or verify that what's inside the ComboBox is not already one item of yours. For example, if you select an Item in the comboBox, the fromString() will be called. But you don't want to create a new ListGroupsObj, you just want to isolate the ListGroupsObj inside your items List and returns it.
Now, you have the guaranty that a call to getValue() on your ComboBox will always return an ListGroupsObj object since you have provided a custom and valid StringConverter.
Here is a simplified and working version of your code :
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class MainApp extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
final ComboBox<ListGroupsObj> comboBox = new ComboBox();
comboBox.setEditable(true);
comboBox.setConverter(new StringConverter<ListGroupsObj>() {
#Override
public String toString(ListGroupsObj obj) {
return obj.toString();
}
#Override
public ListGroupsObj fromString(String obj) {
//Here we try to identify if the given String actually represents one item of our list
for(ListGroupsObj tempObj:comboBox.getItems()){
if(tempObj.toString().equals(obj)){
return tempObj;
}
}
//If not we just create a new one
return ListGroupsObj.newInstance().groupName(obj);
}
});
// Insert Some data
ListGroupsObj ob = ListGroupsObj.newInstance().groupId(12).groupName("Test");
comboBox.getItems().addAll(ob);
ListGroupsObj osb = ListGroupsObj.newInstance().groupId(13).groupName("Test2");
comboBox.getItems().addAll(osb);
comboBox.setValue(ob);
final StackPane layout = new StackPane();
layout.getChildren().add(comboBox);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
stage.setScene(new Scene(layout));
stage.show();
}
public static class ListGroupsObj {
private int groupId;
private String groupName;
public static ListGroupsObj newInstance() {
return new ListGroupsObj();
}
public ListGroupsObj() {
}
public ListGroupsObj groupId(int groupId) {
this.groupId = groupId;
return this;
}
public ListGroupsObj groupName(String groupName) {
this.groupName = groupName;
return this;
}
public int getGroupId() {
return groupId;
}
public String getGroupName() {
return groupName;
}
#Override
public String toString() {
return groupId + " - " + groupName;
}
}
}
PS: The issue was already raised in the official JavaFX issue Tracker, I'll leave the link here since there is another example in the ticket (login required) : https://javafx-jira.kenai.com/browse/RT-29118
I &m trying to expose my data base using a web service , i am using a postgresql data base , ejb 3.1 and , CXF as webservice framework.
This is the entity
package persistance.model;
import java.io.Serializable;
import java.lang.String;
import java.util.Date;
import javax.persistence.*;
/**
* Entity implementation class for Entity: ENVOI
*
*/
#Entity
#Table(name = "Envoi")
#NamedQueries({#NamedQuery(name="Envoi.getAll", query="Select e from Envoi e")})
public class Envoi implements Serializable {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
#Column
private int Numet;
#Column
private int Numseq;
#Column
private int Valadler;
#Column
private String Typemess;
#Column
#Temporal(TemporalType.DATE)
private Date Horodatage;
#Column
private String Appli;
#Column
private String Versproto;
#Column
private String Data;
#Column
private String ACK;
private static final long serialVersionUID = 1L;
public Envoi() {
super();
}
public int getNumet() {
return this.Numet;
}
public void setNumet(int Numet) {
this.Numet = Numet;
}
public int getNumseq() {
return this.Numseq;
}
public void setNumseq(int Numseq) {
this.Numseq = Numseq;
}
public int getValadler() {
return this.Valadler;
}
public void setValadler(int Valadler) {
this.Valadler = Valadler;
}
public String getTypemess() {
return this.Typemess;
}
public void setTypemess(String Typemess) {
this.Typemess = Typemess;
}
public Date getHorodatage() {
return this.Horodatage;
}
public void setHorodatage(Date Horodatage) {
this.Horodatage = Horodatage;
}
public String getAppli() {
return this.Appli;
}
public void setAppli(String Appli) {
this.Appli = Appli;
}
public String getVersproto() {
return this.Versproto;
}
public void setVersproto(String Versproto) {
this.Versproto = Versproto;
}
public int getId() {
return this.Id;
}
public void setId(int Id) {
this.Id = Id;
}
public String getData() {
return this.Data;
}
public void setData(String Data) {
this.Data = Data;
}
public String getACK() {
return this.ACK;
}
public void setACK(String ACK) {
this.ACK = ACK;
}
}
Now here the DAO
this one is generic
package persistance.dao;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
//import javax.persistence.criteria.CriteriaQuery;
public abstract class GenericDAO<T> {
private final static String UNIT_NAME = "MestaPU";
#PersistenceContext(unitName = UNIT_NAME)
private EntityManager em;
private Class<T> entityClass;
public GenericDAO(Class<T> entityClass) {
this.entityClass = entityClass;
}
public void save(T entity) {
em.persist(entity);
}
protected void delete(Object id, Class<T> classe) {
T entityToBeRemoved = em.getReference(classe, id);
em.remove(entityToBeRemoved);
}
public T update(T entity) {
return em.merge(entity);
}
public T find(int entityID) {
return em.find(entityClass, entityID);
}
// Using the unchecked because JPA does not have a
// em.getCriteriaBuilder().createQuery()<T> method
/* #SuppressWarnings({ "unchecked", "rawtypes" })
public List<T> findAll() {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return em.createQuery(cq).getResultList();
}*/
// Using the unchecked because JPA does not have a
// ery.getSingleResult()<T> method
/* #SuppressWarnings("unchecked")
protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
T result = null;
try {
Query query = em.createNamedQuery(namedQuery);
// Method that will populate parameters if they are passed not null and empty
if (parameters != null && !parameters.isEmpty()) {
populateQueryParameters(query, parameters);
}
result = (T) query.getSingleResult();
} catch (Exception e) {
System.out.println("Error while running query: " + e.getMessage());
e.printStackTrace();
}
return result;
}*/
/* private void populateQueryParameters(Query query, Map<String, Object> parameters) {
for (Entry<String, Object> entry : parameters.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
}*/
}
this one is spécifique to Envoi entity
package persistance.dao;
import javax.ejb.Stateless;
import persistance.model.*;
#Stateless
public class EnvoiDAO extends GenericDAO<Envoi> {
public EnvoiDAO() {
super(Envoi.class);
}
public void delete(Envoi envoi) {
super.delete(envoi.getId(), Envoi.class);
}
}
This is the Facade to expose the ejb
package persistance.facade;
import java.util.List;
import javax.ejb.Local;
import javax.jws.WebService;
import persistance.model.Envoi;
#WebService
#Local
public interface EnvoiFacade {
public abstract void save(Envoi envoi);
public abstract Envoi update(Envoi envoi);
public abstract void delete(Envoi envoi);
public abstract Envoi find(int entityID);
public abstract List<Envoi> findAll();
}
package persistance.facade;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import persistance.dao.EnvoiDAO;
import persistance.model.Envoi;
#WebService
#Stateless
public class EnvoiFacadeImp implements EnvoiFacade {
#EJB
private EnvoiDAO envoiDAO;
public void save(Envoi envoi) {
envoiDAO.save(envoi);
}
public Envoi update(Envoi envoi) {
return envoiDAO.update(envoi);
}
public void delete(Envoi envoi) {
envoiDAO.delete(envoi);
}
public Envoi find(int entityID) {
// TODO Auto-generated method stub
return null;
}
public List<Envoi> findAll() {
// TODO Auto-generated method stub
return null;
}
/*public Envoi find(int entityID) {
return envoiDAO.find(entityID);
}*/
/*public List<Envoi> findAll() {
return envoiDAO.findAll();
}*/
}
Now you will find the spring bean that publishes the service
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint
id="orderProcess"
implementor="demo.order.OrderProcessImpl"
address="/OrderProcess" />
<jaxws:endpoint
id="EnvoiFacade"
implementor="persistance.facade.EnvoiFacadeImp"
address="/EnvoiFacade" />
</beans>
Now you'll find the client and the bean associated to it
package demo.ejb.client;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import persistance.facade.EnvoiFacade;
import persistance.model.Envoi;
public final class Client {
public Client() {
}
public static void main(String args[]) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "demo/ejb/client/client-beans.xml" });
EnvoiFacade client = (EnvoiFacade) context.getBean("envoiClient");
Envoi p1 = new Envoi();
p1.setNumet(3690);
p1.setNumseq(9990);
client.save(p1);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<jaxws:client id="envoiClient" serviceClass="persistance.facade.EnvoiFacade" address="http://localhost:8080/orderapp/EnvoiFacade" >
</jaxws:client>
</beans>
Now my webservice deploy just fin in JBOSS 7.1.0 AS , i created the datasources and included the driver for postgres my sql , the problem is when a run the client i get this error
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Fault occurred while processing.
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:143)
at $Proxy57.save(Unknown Source)
at demo.ejb.client.Client.main(Client.java:23)
Caused by: org.apache.cxf.binding.soap.SoapFault: Fault occurred while processing.
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.unmarshalFault(Soap11FaultInInterceptor.java:75)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:46)
at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:35)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:96)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:69)
at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:34)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:658)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:2139)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:2022)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1947)
at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:66)
at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:632)
at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:472)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:302)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:254)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:73)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:123)
... 2 more
I had a similar stack trace recently and I found out I was missing a classic setter on one of my fields.
I am just trying out examples of entity beans. I am using JBOSS 4.0.0, EJB 2.0, MyEclipse 8.6. Reason for using JBOSS 4.0.0 and EJB 2.0 is just for learning sake. I am reading head first book. In the process help me if I made any mistakes. I wrote a build file using ant to deploy this in deploy directory of JBOSS. Don't know where I went wrong, but struggling with error. I am getting this error:
java.lang.NullPointerException
at org.jboss.ejb.plugins.local.LocalHomeProxy.invoke(LocalHomeProxy.java:118)
at $Proxy0.findByPrimaryKey(Unknown Source)
at AccesesPackage.DirectorMovie.go(DirectorMovie.java:24)
at AccesesPackage.DirectorMovie.main(DirectorMovie.java:13)
Thank you in advance.
My ejb-jar.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<display-name>EJB1</display-name>
<enterprise-beans>
<session>
<display-name>AdviceBean</display-name>
<ejb-name>AdviceBean</ejb-name>
<home>headfirst.AdviceHome</home>
<remote>headfirst.Advice</remote>
<ejb-class>headfirst.AdviceBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
<session>
<display-name>AdviceStatefullBean</display-name>
<ejb-name>AdviceStatefullBean</ejb-name>
<home>headfirstStatefull.AdviceHomeStatefull</home>
<remote>headfirstStatefull.AdviceStatefull</remote>
<ejb-class>headfirstStatefull.AdviceStatefullBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Bean</transaction-type>
</session>
<entity>
<display-name>MovieBean</display-name>
<ejb-name>MovieBean</ejb-name>
<local-home>movie.MovieHome</local-home>
<local>movie.Movie</local>
<ejb-class>movie.MovieBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>moviebean</abstract-schema-name>
<cmp-field><field-name>movieId</field-name></cmp-field>
<cmp-field><field-name>title</field-name></cmp-field>
<cmp-field><field-name>genre</field-name></cmp-field>
<cmp-field><field-name>directorId</field-name></cmp-field>
<cmp-field><field-name>year</field-name></cmp-field>
<primkey-field>movieId</primkey-field>
<security-identity>
<use-caller-identity></use-caller-identity>
</security-identity>
<query>
<query-method>
<method-name>findByPrimaryKey</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(m) FROM moviebean m WHERE m.movieId = ?1</ejb-ql>
</query>
</entity>
<entity>
<display-name>DirectorBean</display-name>
<ejb-name>DirectorBean</ejb-name>
<local-home>director.DirectorHome</local-home>
<local>director.Director</local>
<ejb-class>director.DirectorBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-version>2.x</cmp-version>
<abstract-schema-name>directorbean</abstract-schema-name>
<cmp-field><field-name>directorId</field-name></cmp-field>
<cmp-field><field-name>oscarWinner</field-name></cmp-field>
<cmp-field><field-name>degrees</field-name></cmp-field>
<cmp-field><field-name>name</field-name></cmp-field>
<primkey-field>directorId</primkey-field>
<security-identity>
<use-caller-identity></use-caller-identity>
</security-identity>
<query>
<query-method>
<method-name>findByPrimaryKey</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(d) FROM directorbean d WHERE d.directorId = ?1</ejb-ql>
</query>
<query>
<query-method>
<method-name>ejbSelectGetAllMovies</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT OBJECT(m) FROM moviebean m WHERE m.directorId = ?1</ejb-ql>
</query>
</entity>
</enterprise-beans>
<relationships>
<ejb-relation>
<ejb-relationship-role>
<ejb-relationship-role-name>Director-directs-many-movies</ejb-relationship-role-name>
<multiplicity>One</multiplicity>
<relationship-role-source>
<ejb-name>DirectorBean</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>movies</cmr-field-name>
<cmr-field-type>java.util.Collection</cmr-field-type>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Movie-has-one-director-only</ejb-relationship-role-name>
<multiplicity>Many</multiplicity>
<cascade-delete />
<relationship-role-source>
<ejb-name>MovieBean</ejb-name>
</relationship-role-source>
</ejb-relationship-role>
</ejb-relation>
</relationships>
</ejb-jar>
My jboss.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>AdviceBean</ejb-name>
<jndi-name>Advisor</jndi-name>
</session>
<session>
<ejb-name>AdviceStatefullBean</ejb-name>
<jndi-name>AdvisorStatefull</jndi-name>
</session>
<entity>
<ejb-name>MovieBean</ejb-name>
<local-jndi-name>movies</local-jndi-name>
</entity>
<entity>
<ejb-name>DirectorBean</ejb-name>
<local-jndi-name>directors</local-jndi-name>
</entity>
</enterprise-beans>
</jboss>
My Director package:
Director Bean:
package director;
import java.rmi.RemoteException;
import javax.ejb.;
import java.util.;
import movie.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import AccesesPackage.ConnectionPool;
public abstract class DirectorBean implements EntityBean {
private EntityContext context;
public void ejbActivate() throws EJBException{
System.out.println("Inside director ejb activate method");
}
public void ejbLoad() throws EJBException {
System.out.println("Inside director ejb load method");
}
public void ejbPassivate() throws EJBException{
System.out.println("Inside director ejb passivate method");
}
public void ejbRemove() throws RemoveException, EJBException{
System.out.println("Inside director ejb remove method");
}
public void ejbStore() throws EJBException{
System.out.println("Inside director ejb store method");
}
public void setEntityContext(EntityContext arg0) throws EJBException{
this.context = arg0;
System.out.println("Inside director ejb set entity context method");
}
public void unsetEntityContext() throws EJBException{
System.out.println("Inside director ejb unset entity context method");
}
public abstract void setDirectorId(String id);
public abstract String getDirectorId();
public abstract void setOscarWinner(boolean b);
public abstract boolean getOscarWinner();
public abstract void setDegrees(String m);
public abstract String getDegrees();
public abstract void setName(String name);
public abstract String getName();
public abstract Collection getMovies();
public abstract void setMovies(Collection movies);
public abstract Collection ejbSelectGetAllMovies(String directorId) throws FinderException;
public String directorName(){
return this.getName();
}
public java.lang.String ejbCreate(String directorId, boolean isOscar, String degrees, String name) throws CreateException {
this.setDirectorId(directorId);
this.setOscarWinner(isOscar);
this.setDegrees(degrees);
this.setName(name);
return directorId;
}
public void ejbPostCreate(String directorId, boolean isOscar, String degrees, String name) throws CreateException {
}
public Collection getAllMovies() {
Collection coll = null;
try{
coll = this.ejbSelectGetAllMovies(this.getDirectorId());
}catch(Exception ex){
ex.printStackTrace();
}
return coll;
}
public void changeOscarStatus(String b){
Connection con= null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/ejbpr","root","chaitanya");
String sql1 = "UPDATE director SET degrees = ? where directorId = ?";
PreparedStatement pstmt = conn.prepareStatement(sql1);
pstmt.setString(1, b);
pstmt.setString(2, this.getDirectorId());
boolean update = pstmt.execute();
conn.close();
System.out.println(update);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
Director Home:
package director;
import javax.ejb.;
import java.util.;
public interface DirectorHome extends EJBLocalHome {
public Director create(String directorId, boolean isOscar, String degrees, String name) throws CreateException;
public Director findByPrimaryKey(String directorId) throws FinderException;
}
Director component interface:
package director;
import javax.ejb.;
import java.util.;
public interface Director extends EJBLocalObject {
public void changeOscarStatus(String st);
public String directorName();
public Collection getAllMovies();
}
My Movie package:
Movie Bean:
package movie;
import java.rmi.RemoteException;
import javax.ejb.;
import director.;
import java.util.*;
import javax.naming.*;
import javax.rmi.PortableRemoteObject;
public abstract class MovieBean implements EntityBean {
private EntityContext context = null;
public void ejbActivate() throws EJBException {
System.out.println("Inside movie ejb activate method");
}
public void ejbLoad() throws EJBException {
System.out.println("Inside movie ejb load method");
}
public void ejbPassivate() throws EJBException {
System.out.println("Inside movie ejb passivate method");
}
public void ejbRemove() throws RemoveException, EJBException {
System.out.println("Inside movie ejb remove method");
}
public void ejbStore() throws EJBException, RemoteException {
System.out.println("Inside movie ejb store method");
}
public void setEntityContext(EntityContext arg0) throws EJBException {
this.context = arg0;
System.out.println("Inside movie ejb set entity context method");
}
public void unsetEntityContext() throws EJBException {
System.out.println("Inside movie ejb unset entity context method");
}
public String getMovieTitle(){
return this.getTitle();
}
public String getMovieDirectorId(){
return this.getDirectorId();
}
public String getMovieDirectorName(String directorId){
String name= null;
try{
Properties properties = new Properties();
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url","localhost:1099");
Context ic = new InitialContext(properties);
Object d = ic.lookup("directors");
DirectorHome dir0 = (DirectorHome)PortableRemoteObject.narrow(d, DirectorHome.class);
Director direct0 = dir0.findByPrimaryKey(directorId);
name= direct0.directorName();
}catch(Exception ex){ex.printStackTrace();}
return name;
}
public abstract String getMovieId();
public abstract void setMovieId(String movieId);
public abstract String getTitle();
public abstract void setTitle(String title);
public abstract String getYear();
public abstract void setYear(String year);
public abstract String getGenre();
public abstract void setGenre(String genre);
public abstract void setDirectorId(String directorId);
public abstract String getDirectorId();
public abstract void setDirector(Director director);
public abstract Director getDirector();
public java.lang.String ejbCreate(String movieId, String title, String year, String genre, String directorId) throws CreateException {
this.setMovieId(movieId);
this.setTitle(title);
this.setYear(year);
this.setGenre(genre);
this.setDirectorId(directorId);
return movieId;
}
public void ejbPostCreate(String movieId, String title, String year, String genre, String directorId) throws CreateException{
}
}
Movie Home:
package movie;
import javax.ejb.;
import java.util.;
public interface MovieHome extends EJBLocalHome {
public Movie create(String movieId, String title, String year, String genre, String directorId) throws CreateException;
public Movie findByPrimaryKey(String Key) throws FinderException;
}
Movie component interface:
package movie;
import javax.ejb.*;
public interface Movie extends EJBLocalObject {
public String getMovieTitle();
public String getMovieDirectorName(String directorId);
public String getMovieDirectorId();
}
Finally my client:
package AccesesPackage;
import javax.naming.*;
import java.rmi.*;
import javax.rmi.*;
import movie.*;
import director.*;
import javax.ejb.*;
import java.util.*;
public class DirectorMovie {
//public static final String localJndiName= "local/"+DirectorBean.class.getSimpleName();
public static void main(String[] args){
new DirectorMovie().go();
}
public void go(){
try{
Properties properties = new Properties();
properties.put("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url","localhost:1099");
Context ic = new InitialContext(properties);
DirectorHome dir0 = (DirectorHome)ic.lookup("directors");
dir0.findByPrimaryKey("1");
//DirectorHome dir0 = (DirectorHome)PortableRemoteObject.narrow(d, DirectorHome.class);
// Director direct0 = dir0.create("1", true, "3", "Chaitanya");
//Collection col = direct0.getAllMovies();
//if(col.isEmpty()){
// System.out.println("The returned collection is empty");
//}
//else{
// Iterator ita = col.iterator();
// if (ita.hasNext()){
// Movie movieName = (Movie)ita.next();
// System.out.println(movieName.getMovieTitle());
// }
//}
//System.out.println(direct0.directorName());
//MovieHome mov0 = (MovieHome)ic.lookup("movies");
//MovieHome mov0 = (MovieHome)PortableRemoteObject.narrow(m, MovieHome.class);
//Movie movie0 = mov0.create("M1", "Men In Black", "2001", "Action", "1");
//System.out.println(movie0.getMovieTitle());
//String mdId = movie0.getMovieDirectorId();
//String directorName = movie0.getMovieDirectorName(mdId);
//System.out.println(directorName);
//System.out.println();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
I think that the reason is you aren't supposed to define the findByPrimaryKey in the ejb-jar.xml.
The container will built it automatically using your deployment descriptor, the findByPrimaryKey is defined only the Home interface.