SimpleJSFNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler - jsf

I'm migrating a JSF 1.2 project to JSF 2 and PrimeFaces 6 with Ultima layout.
When using Ultima layout, I get the below exception:
SimpleJSFNavigationHandler cannot be cast to javax.faces.application.ConfigurableNavigationHandler.
How to fix it?
Below is the SimpleJSFNavigationHandler.
import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.springframework.web.jsf.DecoratingNavigationHandler;
public class SimpleJSFNavigationHandler extends DecoratingNavigationHandler {
public static final String DEFAULT_REDIRECT_PREFIX = "redirect:";
public static final String DEFAULT_FORWARD_PREFIX = "/";
private String redirectPrefix = DEFAULT_REDIRECT_PREFIX;
private String forwardPrefix = DEFAULT_FORWARD_PREFIX;
public SimpleJSFNavigationHandler() {
}
public SimpleJSFNavigationHandler(NavigationHandler originalNavigationHandler) {
super(originalNavigationHandler);
}
#Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome, NavigationHandler originalNavigationHandler) {
if (outcome != null && outcome.startsWith(redirectPrefix)) {
ExternalContext externalContext = facesContext.getExternalContext();
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
String url = outcome.substring(redirectPrefix.length());
String urlParams="";
if(url.indexOf("?")>0)
urlParams = url.substring(url.indexOf("?"));
String redirectPath = viewHandler.getActionURL(facesContext, url);
try {
//System.out.println("MMMMMMMMMMMMMMMM:::::::::::::::::" + urlParams);
externalContext.redirect(externalContext.encodeActionURL(redirectPath+urlParams));
} catch (IOException e) {
throw new FacesException(e.getMessage(), e);
}
facesContext.responseComplete();
} else if (outcome != null && outcome.startsWith(forwardPrefix)) {
ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
//create new view
String newViewId = outcome.substring(forwardPrefix.length());
if (newViewId.length()>0 && newViewId.charAt(0)!='/') {
newViewId = "/" + newViewId;
}
UIViewRoot viewRoot = viewHandler.createView(facesContext, newViewId);
viewRoot.setViewId(newViewId);
facesContext.setViewRoot(viewRoot);
facesContext.renderResponse();
} else {
callNextHandlerInChain(facesContext, fromAction, outcome, originalNavigationHandler);
}
}
}

You don't need Spring's DecoratingNavigationHandler. You can just use JSF's own ConfigurableNavigationHandlerWrapper.
public class SimpleJSFNavigationHandler extends ConfigurableNavigationHandlerWrapper {
private ConfigurableNavigationHandler wrapped;
public SimpleJSFNavigationHandler(ConfigurableNavigationHandler wrapped) {
this.wrapped = wrapped;
}
#Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
if (...) {
// Your original code here.
} else if (...) {
// Your original code here.
} else {
// Update only the last else part as below.
getWrapped().handleNavigation(facesContext, fromAction, outcome);
}
}
#Override
public ConfigurableNavigationHandler getWrapped() {
return wrapped;
}
}
In the upcoming JSF 2.3 this can even be further simplified as per spec issue 1429 which should further reduce boilerplate code in FacesWrapper implementations.
public class SimpleJSFNavigationHandler extends ConfigurableNavigationHandlerWrapper {
public SimpleJSFNavigationHandler(ConfigurableNavigationHandler wrapped) {
super(wrapped);
}
#Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
if (...) {
// Your original code here.
} else if (...) {
// Your original code here.
} else {
// Update only the last else part as below.
getWrapped().handleNavigation(facesContext, fromAction, outcome);
}
}
}

Related

JAXB not unmarshalling all fields

I am working on a JavaFX application which facilitates all kind of sport related training sessions. Each session consists of multiple exercises, whereas each exercise is repeated multiple times in a few sets. I created some test data and marshalled it. As it turned out, some fields of the Exercise class objects were written but not all of them. By adding the #XmlElement(name="someTagName") tag to each getter of each field I managed that all fields are marshalled and the xml file looks like expected. However, when I unmarshall the xml file, only those fields, which were written without the #XmlElement tag are read and most of the fields only have the default value from the constructor. What am I missing in order to unmarshall all fields?
Here is the class that I want to marshall/unmarshall
package domain;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Exercise extends SelectableDomainObj {
protected StringProperty name;
protected StringProperty mediaFilePath;
protected IntegerProperty repsPerSet;
protected IntegerProperty numOfSets;
protected IntegerProperty breakBetweenSetsInSecs;
protected IntegerProperty displayTimeInSecs;
protected DoubleProperty startSpeed;
protected DoubleProperty endSpeed;
protected BooleanProperty withMetronom;
protected BooleanProperty showIntro;
/**
* Set some reasonable default values from lifting domain
*/
public Exercise() {
mediaFilePath = new SimpleStringProperty();
name = new SimpleStringProperty();
numOfSets = new SimpleIntegerProperty(3);
repsPerSet = new SimpleIntegerProperty(8);
breakBetweenSetsInSecs = new SimpleIntegerProperty(60);
displayTimeInSecs = new SimpleIntegerProperty(-1);
startSpeed = new SimpleDoubleProperty(1.0);
endSpeed = new SimpleDoubleProperty(1.0);
withMetronom = new SimpleBooleanProperty(false);
showIntro = new SimpleBooleanProperty(false);
}
#XmlElement(name="name")
public String getName() {
return name.get();
}
public void setName(String name) {
this.name.set(name);
}
public StringProperty nameProperty() {
return name;
}
#XmlElement(name="mediaFilePath")
public String getMediaFilePath() {
return mediaFilePath.get();
}
public void setMediaFilePath(String mediaFilePath) {
this.mediaFilePath.set(mediaFilePath);
}
public StringProperty mediaFilePathProperty() {
return mediaFilePath;
}
#XmlElement(name="repsPerSet")
public Integer getRepsPerSet() {
return repsPerSet.get();
}
public void setRepsPerSet(int repsPerSet) {
this.repsPerSet.set(repsPerSet);
}
public IntegerProperty repsPerSetProperty() {
return repsPerSet;
}
#XmlElement(name="numOfSets")
public int getNumOfSets() {
return numOfSets.get();
}
public void setNumOfSets(int numOfSets) {
this.numOfSets.set(numOfSets);
}
public IntegerProperty numOfSetsProperty() {
return numOfSets;
}
#XmlElement(name="breakBetweenSetsInSec")
public Integer getBreakBetweenSetsInSecs() {
return breakBetweenSetsInSecs.get();
}
public void setBreakBetweenSetsInSecs(int breakBetweenSetsInSecs) {
this.breakBetweenSetsInSecs.set(breakBetweenSetsInSecs);
}
public IntegerProperty displayTimeInSecsProperty() {
return displayTimeInSecs;
}
#XmlElement(name="displayTimeInSecs")
public Integer getDisplayTimeInSecs() {
return displayTimeInSecs.get();
}
public void setDisplayTimeInSecs(int displayTime) {
this.displayTimeInSecs.set(displayTime);
}
public IntegerProperty breakBetweenSetsInSecsProperty() {
return breakBetweenSetsInSecs;
}
#XmlElement(name="showIntro")
public Boolean isShowIntro() {
return showIntro.getValue();
}
public void setShowIntro(boolean showIntro) {
this.showIntro.set(showIntro);
}
public BooleanProperty showIntroProperty() {
return showIntro;
}
#XmlElement(name="withMetronom")
public Boolean isWithMetronom() {
return withMetronom.getValue();
}
public void setWithMetronom(boolean withMetronom) {
this.withMetronom.set(withMetronom);
}
public BooleanProperty withMetronomProperty() {
return withMetronom;
}
#XmlElement(name="startSpeed")
public Double getStartSpeed() {
return startSpeed.get();
}
public void setStartSpeed(double startDuration) {
this.startSpeed.set(startDuration);
}
public DoubleProperty startSpeedProperty() {
return startSpeed;
}
#XmlElement(name="endSpeed")
public Double getEndSpeed() {
return endSpeed.get();
}
public void setEndSpeed(double endDuration) {
this.endSpeed.set(endDuration);
}
public DoubleProperty endSpeedProperty() {
return endSpeed;
}
public double getSpeed(int rep) {
if(getStartSpeed().equals(getEndSpeed())) {
return getStartSpeed();
}
double min, max;
if(getStartSpeed() > getEndSpeed()) {
max = getStartSpeed();
min = getEndSpeed();
} else {
min = getStartSpeed();
max = getEndSpeed();
}
double diff = max - min;
double increment = diff / (getRepsPerSet()-1);
return min + rep * increment;
}
#Override
public String toString() {
return getName();
}
}
I used this to marshall
public void save(Session session) {
try {
JAXBContext jc = JAXBContext.newInstance(Session.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(session, new File(System.getProperty("user.home"), ".sifuSays/sessions/" + session.getName() + ".xml"));
} catch (JAXBException e) {
System.err.println("Cannot save session " + session.getName());
e.printStackTrace();
}
}
which generates the following xml file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Session>
<exerciseList>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>-1</displayTimeInSecs>
<endSpeed>3.0</endSpeed>
<mediaFilePath>Tan Pak Gan.mp4</mediaFilePath>
<name>Solo Tan Pak Gan Drill</name>
<numOfSets>2</numOfSets>
<repsPerSet>3</repsPerSet>
<showIntro>false</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>false</withMetronom>
</exercise>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>-1</displayTimeInSecs>
<endSpeed>1.0</endSpeed>
<mediaFilePath>Chain Punches.mp4</mediaFilePath>
<name>Solo Ein-Arm-Zyklus</name>
<numOfSets>2</numOfSets>
<repsPerSet>4</repsPerSet>
<showIntro>true</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>true</withMetronom>
</exercise>
<exercise>
<selected>true</selected>
<breakBetweenSetsInSec>5</breakBetweenSetsInSec>
<displayTimeInSecs>10</displayTimeInSecs>
<endSpeed>1.0</endSpeed>
<mediaFilePath>birddogs.jpg</mediaFilePath>
<name>Stetching</name>
<numOfSets>1</numOfSets>
<repsPerSet>1</repsPerSet>
<showIntro>true</showIntro>
<startSpeed>1.0</startSpeed>
<withMetronom>false</withMetronom>
</exercise>
</exerciseList>
<breakBetweenExercisesInSec>10</breakBetweenExercisesInSec>
<name>MMA - Solo</name>
</Session>
and this is the unmarshaller code
public ObservableList<Session> loadSessions() {
sessions = FXCollections.observableArrayList();
try {
List<File> xmlSessionFiles = Stream.of(
new File(System.getProperty("user.home"), ".sifuSays/sessions/").listFiles())
.filter(file -> !file.isDirectory())
.filter(file -> file.getName().endsWith("xml"))
.collect(Collectors.toList());
for(File xmlSessionFile: xmlSessionFiles) {
JAXBContext jc = JAXBContext.newInstance(Session.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Session session = (Session) unmarshaller.unmarshal(xmlSessionFile);
sessions.add(session);
}
} catch (JAXBException e) {
System.err.println("Cannot load sessions");
e.printStackTrace();
}
return sessions;
}
While numOfSets is marshalled, repsPerset is not. Neither startSpeed or stopSpeed are unmarshalled and neither withMetronom or showIntro. But name and mediaFilePath are marshalled. What's wrong?
You are mixing up boxed (Double, Integer) and unboxed (double, int) types. I recommend sticking to boxed types for marshalling since otherwise you'll end up with things set to 0 that you weren't expecting.

Storing a http session attribute in database

How can I pass an injected http session attribute (see below), along with other values (informe by the user) and save them using JPA?
The session attribute is correctly displayed and injected, but I need to pass it using the selected to be stored in the database (actually, it passess null).
The JSF:
<p:outputLabel value="UserID (the sessionAttribute):" for="userID" />
<p:inputText id="userID" value="#{userBean.myUser.xChave}" title="userID" />
<p:outputLabel value="Type the Reason:" for="reason" />
<p:inputText id="reason" value="#{viagensController.selected.reason}" />
<!-- updated (just the call to the action method: -->
<p:commandButton actionListener="#{viagensController.saveNew}" value="#{viagensBundle.Save}" update="display,:ViagensListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,ViagensCreateDialog);" />
The bean:
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
#Named(value = "userBean")
#SessionScoped
public class UserBean implements Serializable {
private bean_login myUser;
public bean_login getMyUser() {
return myUser;
}
public void setMyUser(bean_login myUser) {
this.myUser = myUser;
}
#PostConstruct
public void init() {
String uid = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("xChave").toString();
myUser = new bean_login();
myUser.setxChave(uid);
System.out.print("from init:" + myUser.toString());
}
}
The AbstractFacade:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {{ /*impl. ommited*/ }
public List<T> findAll() {{ /*impl. ommited*/ }
public List<T> findRange(int[] range) { /*impl. ommited*/ }
public int count() { /*impl. ommited*/ }
}
The AbstractController (for the selected in JSF above and other methods):
public abstract class AbstractController<T> {
#Inject
private AbstractFacade<T> ejbFacade;
private Class<T> itemClass;
private T selected;
private Collection<T> items;
private enum PersistAction {
CREATE,
DELETE,
UPDATE
}
public AbstractController() {
}
public AbstractController(Class<T> itemClass) {
this.itemClass = itemClass;
}
public T getSelected() {
return selected;
}
// Pass in the currently selected item
public void setSelected(T selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
public Collection<T> getItems() {
if (items == null) {
items = this.ejbFacade.findAll();
}
return items;
}
// Pass in collection of items
public void setItems(Collection<T> items) {
this.items = items;
}
// Apply changes to an existing item to the data layer.
public void save(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Updated");
persist(PersistAction.UPDATE, msg);
}
// Store a new item in the data layer.
public void saveNew(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Created");
persist(PersistAction.CREATE, msg);
if (!isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void delete(ActionEvent event) {/*implementations ommited*/ }
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
this.setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
this.ejbFacade.edit(selected);
} else {
this.ejbFacade.remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = JsfUtil.getRootCause(ex.getCause());
if (cause != null) {
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException excp = (ConstraintViolationException) cause;
for (ConstraintViolation s : excp.getConstraintViolations()) {
JsfUtil.addErrorMessage(s.getMessage());
}
} else {
msg = cause.getLocalizedMessage();
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/viagensBundle").getString("PersistenceErrorOccured"));
}
}
}
// Creates a new instance of an underlying entity and assigns it to Selected property.
public T prepareCreate(ActionEvent event) {
T newItem;
try {
newItem = itemClass.newInstance();
this.selected = newItem;
initializeEmbeddableKey();
return newItem;
} catch (InstantiationException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
return null;
}
// Inform the user interface whether any validation error exist on a page.
public boolean isValidationFailed() {
return JsfUtil.isValidationFailed();
}
// Retrieve all messages as a String to be displayed on the page.
public String getComponentMessages(String clientComponent, String defaultMessage) {
return JsfUtil.getComponentMessages(clientComponent, defaultMessage);
}
}
Thanks in advance.
updated:
The ViagensController:
#Named(value = "viagensController")
#ViewScoped
public class ViagensController extends AbstractController<Viagens> implements Serializable {
//generics:passing JPA Entity class, where the 'reason' in JSF is defined
public ViagensController() {
super(Viagens.class);
}
}
Need to override the save method passing the injected http session value :
#ManagedBean(name = "riscosController")
#ViewScoped
public class RiscosController extends AbstractController<Riscos> {
#EJB
private RiscosFacade ejbFacade;
#Inject
#SessionChave
private String iSessionChave;
private String sessionChave;
private UorPosController matriculaController;
private UorPosController informanteController;
public String getSessionChave(String chave) {
if (sessionChave.isEmpty()) {
sessionChave = iSessionChave;
}
return sessionChave;
}
public void setSessionChave(String sessionChave) {
this.sessionChave = sessionChave;
}
#PostConstruct
#Override
public void init() {
super.setFacade(ejbFacade);
FacesContext context = FacesContext.getCurrentInstance();
matriculaController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
informanteController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
sessionChave = "";
}
#Override
public void saveNew(ActionEvent event) {
this.getSelected().setObs(this.getSessionChave(sessionChave));
super.saveNew(event);
}
}

p:selectManyMenu report validation error (illegal select options) [duplicate]

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I use primefaces's p:selectManyMenu. When I submit the value, it always report validation error Illegal selection options. Can you help to solve this issue?
JSF code:
<h:outputLabel for="scenario" value="GivenStories:" />
<p:selectManyMenu id="givenstoryselect" value="#{anotherDynaFormController.selectedGivenStory}" converter="scenarioConverter" var="g" style="width:500px;height:70px;align:left;" showCheckbox="true" >
<f:selectItems value="#{anotherDynaFormController.givenStorys}" var="scenario" itemLabel="#{scenario.name}" itemValue="#{scenario}" />
<p:column>#{g.name}</p:column>
</p:selectManyMenu>
Bean class:
//converter
#FacesConverter(value="scenarioConverter")
public class ScenarioConverter implements Converter {
public static List<Scenario> scenarioDB = new ArrayList<Scenario>();
private ScenarioDao scenarioDao = new ScenarioDao();
public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
if (submittedValue.trim().equals("")) {
return null;
} else {
try {
int number = Integer.parseInt(submittedValue);
scenarioDB = scenarioDao.findAll();
for (Scenario p : scenarioDB) {
if (p.getId() == number) {
return p;
}
}
} catch(NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid scenario"));
}
}
return null;
}
public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
if (value == null) {
return null;
} else {
return String.valueOf(((Scenario) value).getId());
}
}
}
#ManagedBean
#ViewScoped
public class AnotherDynaFormController extends SuperBean implements Serializable {
private List<Scenario> givenStorys;
private List<Meta> selectedMetas;
private List<Scenario> selectedGivenStory;
private List<ProjectTree> parents;
public DynaFormModel getModel() {
givenStorys = scenarioDao.findAll();
...
}
...
}
Try this generic converter and see if problem still there .
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.WeakHashMap;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
#FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {
private static Map<Object, String> entities = new WeakHashMap<Object, String>();
#Override
public String getAsString(FacesContext context, UIComponent component, Object entity) {
synchronized (entities) {
if (!entities.containsKey(entity)) {
String uuid = UUID.randomUUID().toString();
entities.put(entity, uuid);
return uuid;
} else {
return entities.get(entity);
}
}
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
for (Entry<Object, String> entry : entities.entrySet()) {
if (entry.getValue().equals(uuid)) {
return entry.getKey();
}
}
return null;
}
}
thanks a lot. I have find the reason of this issue. I should overwrite the equals and hashcode method in this object. Then it works.
#Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Scenario))
return false;
return ((Scenario)obj).getId().equals(this.id);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + name.hashCode();
}

#ManagedProperty - access properties Injected from one view scoped bean into another view scoped bean

I have injected one view scoped bean into another view scoped bean , and I can access some properties of the first bean but others appear as null in #PostContruct. How can I see their real value?
Thanks in advance
Update:
I can only see the value of properties updated in #PostContruct of the first bean and not others
Bean 1(SelectOfferMpans)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.corejsf.SofycNavigation;
import sofyc.corejsf.SofycParamNames;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerFindVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
#ManagedBean
#ViewScoped
public class SelectOfferMpans implements Serializable{
/**
* Logger.
*/
private static Logger log = LogginManager.getLogger(SelectOfferMpans.class.getName());
static {
adq_ren_types = new String[2];
}
private final String ID_OFFER_SELECT_MPANS_FORM = "selectMpans";
private String menuOrigin;
/**
* Parametro de busqueda del formulario.
*/
private String registrationNumber;
private List<CustomerFindVO> customerfoundList;
private CustomerFindVO customerfound;
private String companyRegNo;
private String customerId;
private CustomerFindVO selectedCustomer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites;
private List<MpanVO> siteMpans;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private final static String[] adq_ren_types;
private Map<String,String> hh_nhh_types;
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public CustomerFindVO getSelectedCustomer() {
return selectedCustomer;
}
public void setSelectedCustomer(CustomerFindVO selectedCustomer) {
this.selectedCustomer = selectedCustomer;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(String customerId) {
this.customerId = customerId;
}
public String getCompanyRegNo() {
return companyRegNo;
}
public void setCompanyRegNo(String companyRegNo) {
this.companyRegNo = companyRegNo;
}
public List<CustomerFindVO> getCustomerfoundList() {
return customerfoundList;
}
public void setCustomerfoundList(List<CustomerFindVO> customerfoundList) {
this.customerfoundList = customerfoundList;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public CustomerFindVO getCustomerfound() {
return customerfound;
}
public void setCustomerfound(CustomerFindVO customerfound) {
this.customerfound = customerfound;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Creates a new instance of SelectOfferMpans
*/
public SelectOfferMpans() {
}
#PostConstruct
public void init() {
try{
if(log.isDebugEnabled()) {
log.debug("INIT");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
}catch(Exception e)
{
log.error("SearchCustomer:Init", e);
JSFHelper.addErrorMessage("messagesError", e.getMessage());
}
}
public void findCustomer() throws Exception {
CustomerFindVO customer=null;
try{
if (log.isDebugEnabled()) {
log.debug("Searching Customer....");
}
IOffersBean offersBean = BeanInstanceLocator.getOffersBean();
customerfound = offersBean.searchCustomer(companyRegNo);
if (customerfound!=null){
this.setOfferSites(offersBean.getCustomerSites(customerfound.getCustomerId()));
}
else{
this.setOfferSites(null);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
if (log.isDebugEnabled()) {
log.debug("Customer Data Found");
}
} catch (Throwable t) {
log.error("findCustomer:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error searching customer");
}
}
public String goToOffers(){
try{
JSFHelper.addParamToRequest(SofycParamNames.CUSTOMER_ID, customerfound.getCustomerId());
JSFHelper.addParamToRequest(SofycParamNames.OPTION, this.getMenuOrigin());
return SofycNavigation.VIEW_CREATE_OFFERS_PAGE;
} catch (Throwable t) {
log.error("goToOffers:", t);
JSFHelper.addErrorMessage(ID_OFFER_SELECT_MPANS_FORM, "Error navigating to offers page");
return null;
}
}
private SelectItem[] createFilterOptions(String[] data) {
SelectItem[] options = new SelectItem[data.length + 1];
options[0] = new SelectItem("", "Select");
for(int i = 0; i < data.length; i++) {
options[i + 1] = new SelectItem(data[i], data[i]);
}
return options;
}
private SelectItem[] createFilterOptions1(Map<String,String> data, boolean select) {
//SelectItem[] options = new SelectItem[data.size() + 1];
SelectItem[] options;
int i = 0;
if (select==true) {
options = new SelectItem[data.size() + 1];
options[i] = new SelectItem("", "Select");
i++;
}
else{
options = new SelectItem[data.size()];
}
for (Map.Entry e: data.entrySet()) {
options[i] = new SelectItem(e.getKey().toString(), e.getValue().toString());
//options[i + 1] = new SelectItem(e.getValue().toString(),e.getKey().toString());
i++;
}
return options;
}
private Map<String,String> cargaHHNHH() {
Map<String,String> hh_nhh_types= new HashMap<String,String>();
hh_nhh_types.put("HH","HH");
hh_nhh_types.put("NHH","NHH");
return hh_nhh_types;
}
}
Bean 2(CreateOffer) property selectedSites of the first bean appears always as null and It's loaded in findCustomer Method.
package sofyc.backingbean.offer;
import es.iberdrola.configuration.LogginManager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import org.primefaces.event.SelectEvent;
import org.primefaces.event.ToggleEvent;
import org.primefaces.event.UnselectEvent;
import sofyc.bean.BeanInstanceLocator;
import sofyc.bean.IOffersBean;
import sofyc.utils.JSFHelper;
import sofyc.valueobject.CustomerVO;
import sofyc.valueobject.MddMeasurementClassVO;
import sofyc.valueobject.MpanVO;
import sofyc.valueobject.OfferSitesVO;
import sofyc.valueobject.ProfileClassVO;
import sofyc.valueobject.SiteVO;
import sofyc.valueobject.TradebookVO;
#ManagedBean
#ViewScoped
public class CreateOffer implements Serializable {
private static Logger log = LogginManager.getLogger(CreateOffer.class.getName());
/**
* Creates a new instance of CreateOffer
*/
static {
adq_ren_types = new String[2];
}
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
//#ManagedProperty(value="#{selectOfferMpans}")
//private SelectOfferMpans selectOfferMpans;
private OfferSitesVO[] selectedSites;
/*public void setSelectOfferMpans(SelectOfferMpans selectOfferMpans) {
this.selectOfferMpans = selectOfferMpans;
}*/
public void setSelectedSites(OfferSitesVO[] selectedSites) {
this.selectedSites = selectedSites;
}
/**
* Valores posibles de donde viene la pagina.
*/
private final String CREATE_OFFERS_OPTION = "CREATE";
private final String OFFERS_OPTION = "OFFERS";
private String menuOrigin;
/**
* Corresponde a la columna CUSTOMER_ID.
*/
private Integer customerId;
private Map<String,String> managers;
private Date offerFromDate;
private Date offerToDate;
private Date expiryDate;
private Integer tradeBookId;
private String creditScore;
private String consultantMargin;
private String spMargin;
private Integer productId;
private Integer profileClassId;
private String measurementClassId;
private Integer curveId;
/**
* Customer selected.
*/
private CustomerVO customer;
private List<OfferSitesVO> offerSites;
private List<OfferSitesVO> filteredSites;
private OfferSitesVO selectedSite;
private OfferSitesVO[] selectedSites1;
public OfferSitesVO[] getSelectedSites1() {
return selectedSites1;
}
public void setSelectedSites1(OfferSitesVO[] selectedSites1) {
this.selectedSites1 = selectedSites1;
}
private List<MpanVO> siteMpans;
//private final static String[] hh_nhh_types;
private Map<String,String> hh_nhh_types;
private final static String[] adq_ren_types;
//private final static String[] cotOfferTypes;
private Map<String,String> cotOfferTypes;
private Map<String,String> offerType;
private Map<String,String> loadCurve;
//private final static String[] offerType;
//private final static String[] loadCurve;
private SelectItem[] hh_nhh_List;
private SelectItem[] adq_ren_List;
private SelectItem[] cotOfferList;
private String cotOfferSelection;
private String comcOfferSelection;
private String copcOfferSelection;
private String offerTypeSelection;
private String loadCurveSelection;
//La oferta es de tipo HH o NHH
private String offerHH_NHH;
private SelectItem[] offerTypeList;
private SelectItem[] loadCurveList;
/**
* Site selected.
*/
private SiteVO site;
private MpanVO mpan;
private List<SiteVO> sites;
private List<MpanVO> mpans;
private List<TradebookVO> tradeBookList;
private Map<String,Integer> ProductList;
private List<ProfileClassVO> profileClassList;
private List<MddMeasurementClassVO> measurementClassList;
private Map<String,Integer> CurveList;
#PostConstruct
public void init() {
if(log.isDebugEnabled()) {
log.debug("********************** CreateOffer::init **********************");
}
if (getMenuOrigin() == null) {
setMenuOrigin(JSFHelper.getParameterFromView("OPTION"));
if (getMenuOrigin() == null) {
setMenuOrigin((String) JSFHelper.getParameterFromRequest("OPTION"));
}
if (log.isDebugEnabled()) {
log.debug("CREATE OFFER --> guardado en VIEW VAR menuOrigin el "
+ "valor recuperado en la Request del parametro OPTION:: "
+ getMenuOrigin());
}
}
adq_ren_types[0] = "Adquisitions";
adq_ren_types[1] = "Renews";
//Valor por defecto de COT
cotOfferSelection="0";
//Valor por defecto de COMC
comcOfferSelection="0";
//Valor por defecto de COPC
copcOfferSelection="0";
//Valor por defecto de OfferType
offerTypeSelection="0";
//Valor por defecto de loadCurve
loadCurveSelection="0";
offerHH_NHH="NHH";
this.setHh_nhh_types(cargaHHNHH());
//hh_nhh_List = createFilterOptions(hh_nhh_types);
hh_nhh_List = createFilterOptions1(hh_nhh_types,true);
adq_ren_List = createFilterOptions(adq_ren_types);
//cotOfferList = createFilterOptions(cotOfferTypes);
this.setCotOfferTypes(cargaCOT());
cotOfferList = createFilterOptions1(cotOfferTypes,false);
this.setOfferType(cargaofferType());
offerTypeList = createFilterOptions1(offerType,false);
this.setLoadCurve(cargaloadCurve());
loadCurveList = createFilterOptions1(loadCurve,false);
populateRequestParamsInViewVars();
initCustomerInfo();
CurveList = new LinkedHashMap<String,Integer>();
ProductList = new LinkedHashMap<String,Integer>();
//hh_nhh_List = new LinkedHashMap<String,Integer>();
profileClassId=2;
measurementClassId="A";
curveId=1;
tradeBookId=3;
profileClassList = new ArrayList<ProfileClassVO>();
measurementClassList = new ArrayList<MddMeasurementClassVO>();
tradeBookList = new ArrayList<TradebookVO>();
loadProfileClass();
loadMeasurementClass();
loadTradeBook();
}
public void onRowSelect(SelectEvent event) {
//FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
//event.getComponent().
}
public void onRowUnselect(UnselectEvent event) {
//FacesMessage msg = new FacesMessage("Car Unselected", ((Car) event.getObject()).getModel());
//FacesContext.getCurrentInstance().addMessage(null, msg);
}
public String getOfferTypeSelection() {
return offerTypeSelection;
}
public void setOfferTypeSelection(String offerTypeSelection) {
this.offerTypeSelection = offerTypeSelection;
}
public String getLoadCurveSelection() {
return loadCurveSelection;
}
public void setLoadCurveSelection(String loadCurveSelection) {
this.loadCurveSelection = loadCurveSelection;
}
public SelectItem[] getOfferTypeList() {
return offerTypeList;
}
public void setOfferTypeList(SelectItem[] offerTypeList) {
this.offerTypeList = offerTypeList;
}
public SelectItem[] getLoadCurveList() {
return loadCurveList;
}
public void setLoadCurveList(SelectItem[] loadCurveList) {
this.loadCurveList = loadCurveList;
}
public List<ProfileClassVO> getProfileClassList() {
return profileClassList;
}
public void setProfileClassList(List<ProfileClassVO> ProfileClassList) {
this.profileClassList = ProfileClassList;
}
public MpanVO getMpan() {
return mpan;
}
public void setMpan(MpanVO mpan) {
this.mpan = mpan;
}
public List<MpanVO> getMpans() {
return mpans;
}
public void setMpans(List<MpanVO> mpans) {
this.mpans = mpans;
}
public List<SiteVO> getSites() {
return sites;
}
public void setSites(List<SiteVO> sites) {
this.sites = sites;
}
public CustomerVO getCustomer() {
return customer;
}
public void setCustomer(CustomerVO customer) {
this.customer = customer;
}
public SiteVO getSite() {
return site;
}
public void setSite(SiteVO site) {
this.site = site;
}
public String getCreditScore() {
return creditScore;
}
public void setCreditScore(String creditScore) {
this.creditScore = creditScore;
}
public String getConsultantMargin() {
return consultantMargin;
}
public void setConsultantMargin(String consultantMargin) {
this.consultantMargin = consultantMargin;
}
public String getSpMargin() {
return spMargin;
}
public void setSpMargin(String spMargin) {
this.spMargin = spMargin;
}
public List<OfferSitesVO> getOfferSites() {
return offerSites;
}
public void setOfferSites(List<OfferSitesVO> offerSites) {
this.offerSites = offerSites;
}
public List<OfferSitesVO> getFilteredSites() {
return filteredSites;
}
public void setFilteredSites(List<OfferSitesVO> filteredSites) {
this.filteredSites = filteredSites;
}
public SelectItem[] getAdq_ren_List() {
return adq_ren_List;
}
public void setAdq_ren_List(SelectItem[] adq_ren_List) {
this.adq_ren_List = adq_ren_List;
}
public SelectItem[] getHh_nhh_List() {
return hh_nhh_List;
}
public void setHh_nhh_List(SelectItem[] hh_nhh_List) {
this.hh_nhh_List = hh_nhh_List;
}
public Map<String, String> getHh_nhh_types() {
return hh_nhh_types;
}
public void setHh_nhh_types(Map<String, String> hh_nhh_types) {
this.hh_nhh_types = hh_nhh_types;
}
public Map<String, String> getOfferType() {
return offerType;
}
public void setOfferType(Map<String, String> offerType) {
this.offerType = offerType;
}
public Map<String, String> getLoadCurve() {
return loadCurve;
}
public void setLoadCurve(Map<String, String> loadCurve) {
this.loadCurve = loadCurve;
}
public String getOfferHH_NHH() {
return offerHH_NHH;
}
public void setOfferHH_NHH(String OfferHH_NHH) {
this.offerHH_NHH = OfferHH_NHH;
}
public String getMenuOrigin() {
return menuOrigin;
}
public void setMenuOrigin(String menuOrigin) {
this.menuOrigin = menuOrigin;
}
/**
* Metodo que inicializa los valores del cliente.
*/
private void initCustomerInfo() {
this.setSites(new ArrayList<SiteVO>());
this.setMpans(new ArrayList<MpanVO>());
List<OfferSitesVO> offerSitesAux = new ArrayList<OfferSitesVO>();
FacesMessage msg = null;
try{
log.debug("initCustomerInfo: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
this.setCustomer(offerBean.getCustomer(customerId));
this.setManagers(offerBean.getManagerList());
if (CREATE_OFFERS_OPTION.equals(menuOrigin)){
if (selectedSites!=null){
for(int i = 0; i < selectedSites.length; i++){
offerSitesAux.add(selectedSites[i]);
}
}
this.setOfferSites(offerSitesAux);
}
else{
this.setOfferSites(offerBean.getCustomerSites(customerId));
}
this.setHh_nhh_List(offerBean.getHHNHHList());
this.setAdq_ren_List(offerBean.getAdquisitionRenewList());
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer ProductId) {
this.productId = ProductId;
}
public List<TradebookVO> getTradeBookList() {
return tradeBookList;
}
public void setTradebookList(List<TradebookVO> tradeBookList) {
this.tradeBookList = tradeBookList;
}
public List<MddMeasurementClassVO> getMeasurementClassList() {
return measurementClassList;
}
public void setMeasurementClassList(List<MddMeasurementClassVO> MeasurementClassList) {
this.measurementClassList = MeasurementClassList;
}
public Integer getProfileClassId() {
return profileClassId;
}
public void setProfileClassId(Integer ProfileClassId) {
this.profileClassId = ProfileClassId;
}
public String getMeasurementClassId() {
return measurementClassId;
}
public void setMeasurementClassId(String MeasurementClassId) {
this.measurementClassId = MeasurementClassId;
}
public Integer getCurveId() {
return curveId;
}
public void setCurveId(Integer CurveId) {
this.curveId = CurveId;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public Date getOfferFromDate() {
return offerFromDate;
}
public void setOfferFromDate(Date OfferFromDate) {
this.offerFromDate = OfferFromDate;
}
public Date getOfferToDate() {
return offerToDate;
}
public void setOfferToDate(Date OfferToDate) {
this.offerToDate = OfferToDate;
}
public Integer getTradeBookId() {
return tradeBookId;
}
public void setTradeBookId(Integer tradeBookId) {
this.tradeBookId = tradeBookId;
}
public Map<String, String> getManagers() {
return managers;
}
public void setManagers(Map<String, String> managers) {
this.managers = managers;
}
public OfferSitesVO getSelectedSite() {
return selectedSite;
}
public void setSelectedSite(OfferSitesVO selectedSite) {
this.selectedSite = selectedSite;
}
public OfferSitesVO[] getSelectedSites() {
return selectedSites;
}
public List<MpanVO> getSiteMpans() {
return siteMpans;
}
public void setSiteMpans(List<MpanVO> siteMpans) {
this.siteMpans = siteMpans;
}
public String getCopcOfferSelection() {
return copcOfferSelection;
}
public void setCopcOfferSelection(String copcOfferSelection) {
this.copcOfferSelection = copcOfferSelection;
}
public String getComcOfferSelection() {
return comcOfferSelection;
}
public void setComcOfferSelection(String comcOfferSelection) {
this.comcOfferSelection = comcOfferSelection;
}
public Map<String, String> getCotOfferTypes() {
return cotOfferTypes;
}
public void setCotOfferTypes(Map<String, String> cotOfferTypes) {
this.cotOfferTypes = cotOfferTypes;
}
public String getCotOfferSelection() {
return cotOfferSelection;
}
public void setCotOfferSelection(String cotOfferSelection) {
this.cotOfferSelection = cotOfferSelection;
}
public Date getExpiryDate() {
return expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public SelectItem[] getCotOfferList() {
return cotOfferList;
}
public void setCotOfferList(SelectItem[] cotOfferList) {
this.cotOfferList = cotOfferList;
}
private void loadProfileClass() {
FacesMessage msg = null;
try{
log.debug("ProfileClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List ProfileClassLista = offerBean.getProfileClassList(offerHH_NHH);
this.setProfileClassList((ArrayList<ProfileClassVO>) ProfileClassLista);
if(ProfileClassLista == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Profile_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("ProfileClassLista: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
private void loadMeasurementClass() {
FacesMessage msg;
try{
log.debug("MeasurementClass: Start");
IOffersBean offerBean = BeanInstanceLocator.getOffersBean();
List MeasureClassList = offerBean.getMeasurementClassList();
this.setMeasurementClassList((ArrayList<MddMeasurementClassVO>) MeasureClassList);
if(measurementClassList == null){
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"There are not Measurement_class elements",null);
FacesContext.getCurrentInstance().addMessage(null, msg);
}
log.debug("loadMeasurementClass: end");
}catch(Exception e){
msg = new FacesMessage("ERROR "+e.getMessage());
FacesContext.getCurrentInstance().addMessage(null, msg);
log.error("ERROR 2:: "+e.getMessage());
}
}
}
I have injected one request scoped bean into another view scoped bean
You're not allowed to inject a bean into another bean of a wider scope.
As a rule, the following abominations are not allowed :)
#RequestScoped >> #ViewScoped
#ViewScoped >>#SessionScoped
#SessionScoped >> #ApplicationScoped
EDIT (Based on your update): Injecting a property of a bean, as against injecting the bean itself, will result in a static injection. The static injection means that the value that's injected into the target is what's available as at the time of injection. As a the time the following line was executed:
#ManagedProperty(value="#{selectOfferMpans.selectedSites}")
selectedSites is null. So what you should be doing there instead is injecting the entire bean
#ManagedProperty(value="#{selectOfferMpans}")
This way, you'll have access to the current value of whatever variable you're interested in

JAXB issue-- unexpected element

My JAXB parser suddenly stopped working today. It was working for several weeks. I get the following message. I haven't changed this code for several weeks. Wondering if this set up is good.
EDIT 2: Please could somebody help me! I can't figure this out.
EDIT 1:
My acceptance tests running the same code below are working fine. I believe this is a
classloading issue. I am using the JAXB and StAX in the JDK. However, when I deploy to jboss 5.1, I get the error below. Using 1.6.0_26 (locally) and 1.6.0_30 (dev server). Still puzzling over a solution.
unexpected element (uri:"", local:"lineEquipmentRecord"). Expected
elements are
<{}switchType>,<{}leSwitchId>,<{}nodeAddress>,<{}leId>,<{}telephoneSuffix>,<{}leFormatCode>,<{}groupIdentifier>,<{}telephoneNpa>,<{}telephoneLine>,<{}telephoneNxx>
Here is my unmarshalling class:
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
public class PartialUnmarshaller<T> {
XMLStreamReader reader;
Class<T> clazz;
Unmarshaller unmarshaller;
public PartialUnmarshaller(InputStream stream, Class<T> clazz) throws XMLStreamException, FactoryConfigurationError, JAXBException {
this.clazz = clazz;
this.unmarshaller = JAXBContext.newInstance(clazz).createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
#Override
public boolean handleEvent(ValidationEvent event) {
System.out.println(event.getMessage());
return true;
}
});
this.reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
/* ignore headers */
skipElements(XMLStreamConstants.START_DOCUMENT);
/* ignore root element */
reader.nextTag();
/* if there's no tag, ignore root element's end */
skipElements(XMLStreamConstants.END_ELEMENT);
}
public T next() throws XMLStreamException, JAXBException {
if (!hasNext())
throw new NoSuchElementException();
T value = unmarshaller.unmarshal(reader, clazz).getValue();
skipElements(XMLStreamConstants.CHARACTERS, XMLStreamConstants.END_ELEMENT);
return value;
}
public boolean hasNext() throws XMLStreamException {
return reader.hasNext();
}
public void close() throws XMLStreamException {
reader.close();
}
private void skipElements(Integer... elements) throws XMLStreamException {
int eventType = reader.getEventType();
List<Integer> types = new ArrayList<Integer>(Arrays.asList(elements));
while (types.contains(eventType))
eventType = reader.next();
}
}
This class is used as follows:
List<MyClass> lenList = new ArrayList<MyClass>();
PartialUnmarshaller<MyClass> pu = new PartialUnmarshaller<MyClass>(
is, MyClass.class);
while (pu.hasNext()) {
lenList.add(pu.next());
}
The XML being unmarshalled:
<?xml version="1.0" encoding="UTF-8"?>
<lineEquipment>
<lineEquipmentRecord>
<telephoneNpa>333</telephoneNpa>
<telephoneNxx>333</telephoneNxx>
<telephoneLine>4444</telephoneLine>
<telephoneSuffix>1</telephoneSuffix>
<nodeAddress>xxxx</nodeAddress>
<groupIdentifier>LEN</groupIdentifier>
</lineEquipmentRecord>
<lineEquipmentRecord>
<telephoneNpa>111</telephoneNpa>
<telephoneNxx>111</telephoneNxx>
<telephoneLine>2222</telephoneLine>
<telephoneSuffix>0</telephoneSuffix>
<nodeAddress>xxxx</nodeAddress>
<groupIdentifier>LEN</groupIdentifier>
</lineEquipmentRecord>
</lineEquipment>
Finally, here is MyClass:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* This class is used as an envelope to hold Martens
* line equipment information.
* #author spgezf
*
*/
#XmlRootElement(name="lineEquipmentRecord")
public class MyClass {
private String telephoneNpa;
private String telephoneNxx;
private String telephoneLine;
private String telephoneSuffix;
private String nodeAddress;
private String groupIdentifier;
public MyClass(){
}
// Getters and Setters.
#XmlElement(name="telephoneNpa")
public String getTelephoneNpa() {
return telephoneNpa;
}
public void setTelephoneNpa(String telephoneNpa) {
this.telephoneNpa = telephoneNpa;
}
#XmlElement(name="telephoneNxx")
public String getTelephoneNxx() {
return telephoneNxx;
}
public void setTelephoneNxx(String telephoneNxx) {
this.telephoneNxx = telephoneNxx;
}
#XmlElement(name="telephoneLine")
public String getTelephoneLine() {
return telephoneLine;
}
public void setTelephoneLine(String telephoneLine) {
this.telephoneLine = telephoneLine;
}
#XmlElement(name="telephoneSuffix")
public String getTelephoneSuffix() {
return telephoneSuffix;
}
public void setTelephoneSuffix(String telephoneSuffix) {
this.telephoneSuffix = telephoneSuffix;
}
#XmlElement(name="nodeAddress")
public String getNodeAddress() {
return nodeAddress;
}
public void setNodeAddress(String nodeAddress) {
this.nodeAddress = nodeAddress;
}
#XmlElement(name="groupIdentifier")
public String getGroupIdentifier() {
return groupIdentifier;
}
public void setGroupIdentifier(String groupIdentifier) {
this.groupIdentifier = groupIdentifier;
}
}
Thanks, this is classloading issue I couldn't overcome so I abandoned JAXB.
Your PartialUnmarshaller code worked for me. Below is an alternate version that changes the skipElements method that may work better.
import java.io.InputStream;
import java.util.NoSuchElementException;
import javax.xml.bind.*;
import javax.xml.stream.*;
public class PartialUnmarshaller<T> {
XMLStreamReader reader;
Class<T> clazz;
Unmarshaller unmarshaller;
public PartialUnmarshaller(InputStream stream, Class<T> clazz) throws XMLStreamException, FactoryConfigurationError, JAXBException {
this.clazz = clazz;
this.unmarshaller = JAXBContext.newInstance(clazz).createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
#Override
public boolean handleEvent(ValidationEvent event) {
System.out.println(event.getMessage());
return true;
}
});
this.reader = XMLInputFactory.newInstance().createXMLStreamReader(stream);
/* ignore headers */
skipElements();
/* ignore root element */
reader.nextTag();
/* if there's no tag, ignore root element's end */
skipElements();
}
public T next() throws XMLStreamException, JAXBException {
if (!hasNext())
throw new NoSuchElementException();
T value = unmarshaller.unmarshal(reader, clazz).getValue();
skipElements();
return value;
}
public boolean hasNext() throws XMLStreamException {
return reader.hasNext();
}
public void close() throws XMLStreamException {
reader.close();
}
private void skipElements() throws XMLStreamException {
while(reader.hasNext() && !reader.isStartElement()) {
reader.next();
}
}
}

Resources