Spring Bean injection in JSF Converter - spring

I have seen this question has been asked in this forum but following the solutions provided on those posts, I am not able to inject the spring bean in my converter.
Below is the code snippet:
UserConverter.java class:
#ManagedBean
public class UserConverter implements Converter {
private SearchServiceImpl searchService;
public SearchServiceImpl getSearchService() {
return searchService;
}
public void setSearchService(SearchServiceImpl searchService) {
this.searchService = searchService;
}
#Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String submittedValue) {
List<User> users = getSearchService().getAllUsers();
if (submittedValue.trim().equals("")) {
return null;
} else {
try {
int number = Integer.parseInt(submittedValue);
for (User user : users) {
if (user.getId() == number) {
return user;
}
}
} catch(NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid player"));
}
}
return null;
}
#Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
if (value == null || value.equals("")) {
return "";
} else {
return String.valueOf(((User) value).getFirstName());
}
}
}
I am invoking the converter from xhtml like:
<p:autoComplete id="users" value="#{userSearchBean.selecteSearchedUser}" completeMethod="# {userSearchBean.searchFriends}" var="user" itemLabel="#{user.firstName}" itemValue="#{user}" converter="#{userConverter}" forceSelection="true">
</p:autoComplete>
faces-config.xml:
<converter>
<converter-id>userConverter</converter-id>
<converter-class>com.mbeans.UserConverter</converter-class>
<property>
<property-name>searchService</property-name>
<property-class>com.services.SearchServiceImpl</property-class>
<default-value>#{searchService}</default-value>
</property>
</converter>
enter code here
SearchServiceImpl is the spring class that needs to be injected in the UserConverter.java class.
But unable to get any reference of SearchServiceImpl in the UserConverter.java
Thank you in advance for your help.

Related

Register DynamicParameterizedType global

How can i register a global available DynamicParameterizedType in hibernate?
I wrote the following type:
public class QuantityType extends AbstractSingleColumnStandardBasicType<Quantity<?>> implements DynamicParameterizedType {
public static final QuantityType INSTANCE = new QuantityType();
public QuantityType() {
super(DoubleTypeDescriptor.INSTANCE, new QuantityJavaDescriptor(AbstractUnit.ONE));
}
#Override
public String getName() {
return QuantityType.class.getSimpleName();
}
#Override
public void setParameterValues(Properties parameters) {
ParameterType reader = (ParameterType) parameters.get(PARAMETER_TYPE);
if (reader == null) throw new RuntimeException("Not Implemented");
Unit<?> resolvedUnit = resolveUnit(reader);
setJavaTypeDescriptor(new QuantityJavaDescriptor(resolvedUnit));
}
private Unit<?> resolveUnit(ParameterType reader) {...}
}
and registered it with a service registration in hibernate:
public class QuantityTypeRegistration implements TypeContributor {
#Override
public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) {
typeContributions.contributeType(QuantityType.INSTANCE);
}
}
If i use the type in an entity, the wrap/unwrap method of the JavaTypeDescriptor gets called,
but instead of the parameterized JavaTypeDescriptor, the default JavaTypeDescriptor gets called. For some reason the setParameterValues method was not called.
Code: https://github.com/raynigon/unit-api/tree/master/jpa-starter/src/main/java/com/raynigon/unit_api/jpa

springmvc converter doesnot work

I need convert string to enum. I wish I could post a String parameter ,and receive as an enum, but I got a 415 error.Here is my code
Email.java
public class Email {
private String address;
private String subject;
private String content;
private ServiceType service;
public enum ServiceType {
Feedback, PrivatePolicy, TermsOfUse, MotionDetection;
public static ServiceType get(String type) {
for (ServiceType servicetype : values()) {
if (servicetype.toString().equals(type)) {
return servicetype;
}
}
return null;
}
}
}
StringToEnumConverter uesed to convert string to enum
#SuppressWarnings("rawtypes")
public class StringToEnumConverter implements ConverterFactory<String, Enum> {
#SuppressWarnings({ "unchecked" })
#Override
public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
// TODO Auto-generated method stub
return new StringToEnum(targetType);
}
private class StringToEnum<T extends Enum> implements Converter<String, T> {
private final Class<T> enumType;
public StringToEnum(Class<T> enumType) {
this.enumType = enumType;
}
#SuppressWarnings("unchecked")
public T convert(String source) {
if (source.length() == 0) {
return null;
}
return (T) Enum.valueOf(this.enumType, source.trim());
}
}
}
xml inject the converter
<mvc:annotation-driven conversion-service="conversionService" />
<bean id="conversionService"class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.xxx.xxx.utils.StringToEnumConverter" />
</set>
</property>
</bean>
front-end code
$(".test").click(function(){
$(".response-text").html("please wait....");
var postData = {
"address" : $(".email").val(),
"subject" : $(".subject").val(),
"content" : $(".content").val(),
"service" : $(".service").val()
}
var args = {
url: "XXX/emailService_v1.0",
contentType : "application/x-www-form-urlencoded;charset=UTF-8",
type: "post",
data: postData,
success : function(response, currentAjaxOptions){
var str = JSON.stringify(response);
$(".response-text").html(str);
}
}
$.xAjax(args);
});
controller
#RequestMapping(value = "/emailService_v1.0", method = RequestMethod.POST)
#ResponseBody
public JSONObject emailService(#Valid #RequestBody Email email,
BindingResult result) throws Exception {
System.out.println("come in....");
if (result.hasErrors()) {
return genResJsonFromError(result);
} else {
System.out.println(email.getAddress());
JSONObject resJson = emailService.sendEmail(email);
System.out.println(email.getService().toString());
return resJson;
}
}
I just found the StringToEnumConverter.java wan't invoked.
so it give me 415 Unsupported Media Type error.
Wish anyone can help me
Then I add
#Resource(name = "conversionService")
private ConversionService conversionService;
#InitBinder
public void initBinder(DataBinder binder) {
binder.setConversionService(conversionService);
}
in my controller, but it does not work either.

Converter from #PathVariable DomainObject to String? (using ControllerLinkBuilder.methodOn)

I'm trying to call Spring's ControllerLinkBuilder.methodOn() with a non-String type, which always fails. And I don't know which kind of Converter to use and where to register it.
Here's my Controller:
#RestController
#RequestMapping("/companies")
class CompanyController {
#RequestMapping(value="/{c}", method=RequestMethod.GET)
void getIt(#PathVariable Company c) {
System.out.println(c);
Link link = linkTo(methodOn(getClass()).getIt(c));
}
}
The System.out.println(c) works well. My Company Domain object get's fetched from DB. (I'm using DomainClassConverter)
But the other way doesn't work: ConverterNotFoundException: No converter found capable of converting from type #PathVariable Company to type String
Do I just need a Converter<Company, String>? And where should I register it? I tried something within the addFormatters(FormatterRegistry registry) method of WebMvcConfigurationSupport, but it did just display the same error. But after all I'm not sure what exactly I tried...
I had the same issue, it is a bug. If you don't want to do copy & paste on every controller you can try something like this in your WebMvcConfigurationSupport. It works for me.
#Override
public void addFormatters(final FormatterRegistry registry) {
super.addFormatters(registry);
try {
Class<?> clazz = Class.forName("org.springframework.hateoas.mvc.AnnotatedParametersParameterAccessor$BoundMethodParameter");
Field field = clazz.getDeclaredField("CONVERSION_SERVICE");
field.setAccessible(true);
DefaultFormattingConversionService service = (DefaultFormattingConversionService) field.get(null);
for (Converter<?, ?> converter : beanFactory.getBeansOfType(Converter.class).values()) {
service.addConverter(converter);
}
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
Found a "solution". It requires a lot copy & paste from Spring's classes, but at least it works!
Basically I had to copy org.springframework.hateoas.mvc.AnnotatedParametersParameterAccessor and change two lines:
class AnnotatedParametersParameterAccessor {
...
static class BoundMethodParameter {
// OLD: (with this one you can't call addConverter())
// private static final ConversionService CONVERSION_SERVICE = new DefaultFormattingConversionService();
// NEW:
private static final FormattingConversionService CONVERSION_SERVICE = new DefaultFormattingConversionService();
...
public BoundMethodParameter(MethodParameter parameter, Object value, AnnotationAttribute attribute) {
...
// ADD:
CONVERSION_SERVICE.addConverter(new MyNewConverter());
}
...
}
This class get's used by ControllerLinkBuilderFactory. So I had to copy & paste that, too.
And this one get's used by ControllerLinkBuilder. Also copy & paste.
My Converter just does myDomainObject.getId().toString():
public class MyNewConverter implements Converter<Company, String> {
#Override
public String convert(Company source) {
return source.getId().toString();
}
}
Now you can use the copy&pasted ControllerLinkBuilder inside the controller and it works as expected!
I developed a framework to render links in spring hateoas and it supports annotated parameters (#PathVariable and #RequestParam) and arbitrary parameters types.
In order to render these arbitrary types you have to create a spring bean that implements com.github.osvaldopina.linkbuilder.argumentresolver.ArgumentResolver interface.
The interface has 3 methods:
public boolean resolveFor(MethodParameter methodParameter)
Is used to determine if the ArgumentResolver can be used to deal with the methodParameter. For example:
public boolean resolveFor(MethodParameter methodParameter) {
return UserDefinedType.class.isAssignableFrom(methodParameter.getParameterType());
}
Defines that this ArgumentResover will be used for UserDefinedType.
public void augmentTemplate(UriTemplateAugmenter uriTemplateAugmenter, MethodParameter methodParameter)
Is used to include in the uriTemplate associated with the method the proper template parts. For example:
#Override
public void augmentTemplate(UriTemplateAugmenter uriTemplateAugmenter, MethodParameter methodParameter) {
uriTemplateAugmenter.addToQuery("value1");
uriTemplateAugmenter.addToQuery("value2");
}
adds 2 query parameters (value1 and value2) to the uri template.
public void setTemplateVariables(UriTemplate template, MethodParameter methodParameter, Object parameter, List<String> templatedParamNames)
Sets in the template the values for the template variables. For example:
#Override
public void setTemplateVariables(UriTemplate template, MethodParameter methodParameter, Object parameter, List<String> templatedParamNames) {
if (parameter != null && ((UserDefinedType) parameter).getValue1() != null) {
template.set("value1", ((UserDefinedType) parameter).getValue1());
}
else {
template.set("value1", "null-value");
}
if (parameter != null && ((UserDefinedType) parameter).getValue2() != null) {
template.set("value2", ((UserDefinedType) parameter).getValue2());
}
else {
template.set("value2", "null-value");
}
}
gets the UserDefinedType instance and use it to sets the templates variables value1 and value2 defined in augmentTemplate method.
A ArgumentResolver complete example would be:
#Component
public class UserDefinedTypeArgumentResolver implements ArgumentResolver {
#Override
public boolean resolveFor(MethodParameter methodParameter) {
return UserDefinedType.class.isAssignableFrom(methodParameter.getParameterType());
}
#Override
public void augmentTemplate(UriTemplateAugmenter uriTemplateAugmenter, MethodParameter methodParameter) {
uriTemplateAugmenter.addToQuery("value1");
uriTemplateAugmenter.addToQuery("value2");
}
#Override
public void setTemplateVariables(UriTemplate template, MethodParameter methodParameter, Object parameter, List<String> templatedParamNames) {
if (parameter != null && ((UserDefinedType) parameter).getValue1() != null) {
template.set("value1", ((UserDefinedType) parameter).getValue1());
}
else {
template.set("value1", "null-value");
}
if (parameter != null && ((UserDefinedType) parameter).getValue2() != null) {
template.set("value2", ((UserDefinedType) parameter).getValue2());
}
else {
template.set("value2", "null-value");
}
}
}
and for the following link builder:
linksBuilder.link()
.withRel("user-type")
.fromControllerCall(RootRestController.class)
.queryParameterForUserDefinedType(new UserDefinedType("v1", "v2"));
to the following method:
#RequestMapping("/user-defined-type")
#EnableSelfFromCurrentCall
public void queryParameterForUserDefinedType(UserDefinedType userDefinedType) {
}
would generate the following link:
{
...
"_links": {
"user-type": {
"href": "http://localhost:8080/user-defined-type?value1=v1&value2=v2"
}
...
}
}
full config in spring boot. same as Franco Gotusso's answer just provide more detail.
```
/**
* This configuration file is to fix bug of Spring Hateoas.
* please check https://github.com/spring-projects/spring-hateoas/issues/118.
*/
#Component
public class MvcConfig extends WebMvcConfigurerAdapter {
#Autowired
private ApplicationContext applicationContext;
#Override
public void addFormatters(final FormatterRegistry registry) {
super.addFormatters(registry);
try {
Class<?> clazz = Class.forName("org.springframework.hateoas.mvc."
+ "AnnotatedParametersParameterAccessor$BoundMethodParameter");
Field field = clazz.getDeclaredField("CONVERSION_SERVICE");
field.setAccessible(true);
DefaultFormattingConversionService service =
(DefaultFormattingConversionService) field.get(null);
for (Formatter<?> formatter : applicationContext
.getBeansOfType(Formatter.class).values()) {
service.addFormatter(formatter);
}
for (Converter<?, ?> converter : applicationContext
.getBeansOfType(Converter.class).values()) {
service.addConverter(converter);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
```

Primefaces how to get POJO from selectOneMenu

My question is how to get value from selection in 'selectOneMenu' component. I use POJO not String type. I try to display the name property of selected object in inputText. I use commandButton to refresh value in inputText as in code below. But the problem is that nothing appears in inputText. I'm not sure there is need to use converter but I tried and it also hasn't worked.
here is my .jsp file:
<p:selectOneMenu value="#{appointentBean.selectedSpecialization}">
<f:selectItems value="#{appointentBean.specializationResult}" var="i" itemValue="#{i}" itemLabel="#{i.name}"/>
</p:selectOneMenu>
<p:commandButton value="Szukaj" >
<p:ajax update="textid" />
</p:commandButton>
<p:inputText id="textid" value="#{appointentBean.selectedSpecialization.name}" />
appointmentBean:
#ManagedBean
#ViewScoped
#SessionScoped
public class appointentBean
{
private ArrayList<Specialization> specializationResult;
private Specialization selectedSpecialization;
public ArrayList<Specialization> getSpecializationResult()
{
//Here retrievie objects list from database and it works
return specializationResult;
}
public void setSpecializationResult(ArrayList<Specialization> result) {
this.specializationResult = result;
}
public Specialization getSelectedSpecialization() {
return selectedSpecialization;
}
public void setSelectedSpecialization(Specialization selectedSpecialization) {
this.selectedSpecialization = selectedSpecialization;
}
}
Specialization.java:
#Entity
#Table(name="Specializations")
public class Specialization
{
#Id
#GeneratedValue
private int specialization_id;
#Column(name="name")
private String name;
public int getSpecialization_id() {
return specialization_id;
}
public void setSpecialization_id(int specialization_id) {
this.specialization_id = specialization_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
What is more. If I do not make selection on the list NullPointerExcetion appears. But when I make choice i doesn't. So the object is set after selection.
Give a name to your Managed Bean like this
1. #ManagedBean(name ="appointentBean")
2. It should be in Session Scoped or View Scoped not in Both
Your code works perfectly on my End. I did changes to
ArrayList<Specialization> getSpecializationResult() like this:
public ArrayList<Specialization> getSpecializationResult()
{
//Here retrievie objects list from database and it works
specializationResult = new ArrayList<Specialization>();
Specialization specialize= new Specialization();
specialize.setName("Vinayak");
specialize.setSpecialization_id(1);
specializationResult.add(specialize);
return specializationResult;
}
It worked . So, make the necessary changes and let us know.
EDIT 2
Whenever we Deal with POJO's at that time we have to deal with Converter.
Why Custom Converter is the question is what you want to ask now. Refer Custom Converter
These are the steps to create Custom Converter
1. Create a converter class by implementing javax.faces.convert.Converter interface.
2. Override both getAsObject() and getAsString() methods.
3. Assign an unique converter ID with #FacesConverter annotation present in javax.annotation.
First of all I have created a POJOConverter class for your Specialization class
package primefaces1;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
#FacesConverter(forClass=Specialization.class)
public class PojoConverter implements Converter{
public static List<Specialization> specilizationObject;
static {
specilizationObject = new ArrayList<Specialization>();
specilizationObject.add(new Specialization("Vinayak", 10));
specilizationObject.add(new Specialization("Pingale", 9));
}
public Object getAsObject(FacesContext facesContext, UIComponent
component, String submittedValue) {
if (submittedValue.trim().equals("")) {
return null;
} else {
try {
for (Specialization p : specilizationObject) {
if (p.getName().equals(submittedValue)) {
return p;
}
}
} catch(NumberFormatException exception) {
throw new ConverterException(new
FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion
Error", "Not a valid Specialization"));
}
}
return null;
}
public String getAsString(FacesContext facesContext, UIComponent
component, Object value) {
if (value == null || value.equals("")) {
return "";
} else {
return String.valueOf(((Specialization) value).getName());
}
}
}
Following changes has been made to your managed Bean class. To overcome the NUll Pointer Exception
package primefaces1;
import java.util.ArrayList;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "appointentBean")
#SessionScoped
public class appointentBean {
private ArrayList<Specialization> specializationResult;
private Specialization selectedSpecialization ;
#PostConstruct
public void init() {
selectedSpecialization = new Specialization();
selectedSpecialization.setName(new String());
selectedSpecialization.setSpecialization_id(0);
}
public appointentBean() {
specializationResult= (ArrayList<Specialization>)
PojoConverter.specilizationObject;
}
public ArrayList<Specialization> getSpecializationResult() {
// Here retrievie objects list from database
//and it works
return specializationResult;
}
public void setSpecializationResult(ArrayList<Specialization> result) {
this.specializationResult = result;
}
public Specialization getSelectedSpecialization() {
if (this.selectedSpecialization != null)
System.out.println("getSelectedSpecialization----"
+ this.selectedSpecialization.getName());
return this.selectedSpecialization;
}
public void setSelectedSpecialization(Specialization
selectedSpecialization) {
this.selectedSpecialization = selectedSpecialization;
}
}
I have made some minute changes to your xhtml for showing values.
<h:body>
<h:form id="me">
<p:selectOneMenu value="#{appointentBean.selectedSpecialization}" >
<f:selectItem itemLabel="Select One" itemValue=""></f:selectItem>
<f:selectItems value="#{appointentBean.specializationResult}"
var="result" itemValue="#{result}" itemLabel="#{result.name}" />
</p:selectOneMenu>
<p:commandButton value="Szukaj" update="me:textid">
</p:commandButton>
<h:outputText value="NAME: "></h:outputText>
<h:outputText id="textid" value="#{appointentBean.selectedSpecialization.name}" rendered="#{not empty appointentBean.selectedSpecialization}"/>
</h:form>
</h:body>
I find myself in the same situation that user2374573, SelectOneMenu, was populated correctly using a custom converter, but the selected item was null. The proposed solution is a variation of the custom converter, but it doesn't solve the problem (at least for me). The value selecting does not arrive as explained in the Primefaces documentation, this occurs because SelectOneMenu operates with String and not with Pojos. After studying In the end I have opted for an intermediate solution.
Instead of having a variable of type pojo to store the value, I use just having a String that stores the id of the element as follows.
This solution has been useful for the SelectOneMenu and also for loading the Targer in the DualList used in the Primefaces Picklist. It is not an ideal solution, but it saves the problem.
Java View
public class PickListView implements Serializable {
private static final long serialVersionUID = 1L;
private List<CviConcesione> listaConcesion;
private CviConcesione concesionSeleccionada;
private String concesionSeleccionadaS;
#Autowired
private ConcesionesBO concesionesBO;
#PostConstruct
public void init() {
}
public List<CviConcesione> getListaConcesion() {
if (null != listaConcesion && !listaConcesion.isEmpty()) {
return listaConcesion;
} else {
listaConcesion = new ArrayList<CviConcesione>();
listaConcesion = concesionesBO.consultaTodasConcesiones();
return listaConcesion;
}
}
public void setListaConcesion(List<CviConcesione> listaConcesion) {
this.listaConcesion = listaConcesion;
}
public ConcesionesBO getConcesionesBO() {
return concesionesBO;
}
public void setConcesionesBO(ConcesionesBO concesionesBO) {
this.concesionesBO = concesionesBO;
}
public CviConcesione getConcesionSeleccionada() {
return concesionSeleccionada;
}
public void setConcesionSeleccionada(CviConcesione concesionSeleccionada) {
this.concesionSeleccionada = concesionSeleccionada;
}
public String getConcesionSeleccionadaS() {
return concesionSeleccionadaS;
}
public void setConcesionSeleccionadaS(String concesionSeleccionadaS) {
this.concesionSeleccionadaS = concesionSeleccionadaS;
}
}
Html Code for select one menu
<p:selectOneMenu
id="concesionR"
value="#{pickListView.concesionSeleccionadaS}"
style="width:125px"
dynamic="true"
converter="#{concesionConverter}">
<f:selectItem itemLabel="Seleccione" itemValue="" />
<f:selectItems value="#{pickListView.listaConcesion}"
var="concesion"
itemLabel="#{concesion.conCodigo} - #{concesion.conDescripcion}"
itemValue="#{concesion.conCodigo}"
ajax = "true"
/>
<p:ajax update="lineaR" process="#form" />
</p:selectOneMenu>
a
Class converter
#FacesConverter("concesionConverter")
public class ConcesionesConverter implements Converter {
public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
if(value != null && value.trim().length() > 0) {
try {
PickListView service = (PickListView) fc.getExternalContext().getApplicationMap().get("pickListView");
return service.getListaConcesion().get(Integer.parseInt(value));
} catch(NumberFormatException e) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
}
}
else {
return null;
}
}
public String getAsString(FacesContext fc, UIComponent uic, Object object) {
if(object != null) {
return String.valueOf(((CviConcesione) object).getConId());
}
else {
return null;
}
}
}
This solution does not manage to bring the pojo, but lets you know that it has been selected, showing pojo values.

smartgwt listgrid RestDataSource not populating

Im new using this front end framework application...
I recently started to work with smartgwt and i'm bulding a new application with a Spring MVC integration.
I'm using a ListGrid with a RestDataSource (Consume the Rest service with mvc:annotation-driven for plain JSON)
I can see that the servaice gets consuming properly perhaps my grid is never shown with the data in it.
Can someone help me here ?
Here's my ListGrid class
public class ListGrid extends com.smartgwt.client.widgets.grid.ListGrid {
private final SpringJSONDataSource springJSONDataSource;
public ListGrid(List<DataSourceField> fields) {
this(new PatientDataSource(fields));
}
public ListGrid(SpringJSONDataSource springJSONDataSource) {
this.springJSONDataSource = springJSONDataSource;
init();
}
private void init() {
setAutoFetchData(true);
setAlternateRecordStyles(true);
setEmptyCellValue("???");
setDataPageSize(50);
setDataSource(springJSONDataSource);
}
}
Now there's the DataSource implmentation
public abstract class SpringJSONDataSource extends RestDataSource {
protected final HTTPMethod httpMethod;
public SpringJSONDataSource(List<DataSourceField> fields) {
this(fields, HTTPMethod.POST);
}
public SpringJSONDataSource(List<DataSourceField> fields, HTTPMethod httpMethod) {
this.httpMethod = httpMethod;
setDataFormat(DSDataFormat.JSON);
addDataSourceFields(fields);
setOperationBindings(getFetch());
addURLs();
}
private void addURLs() {
if(getUpdateDataURL() != null)
setUpdateDataURL(getUpdateDataURL());
if(getRemoveDataURL() != null)
setRemoveDataURL(getRemoveDataURL());
if(getAddDataURL() != null)
setAddDataURL(getAddDataURL());
if(getFetchDataURL() != null)
setFetchDataURL(getFetchDataURL());
}
private void addDataSourceFields(List<DataSourceField> fields) {
for (DataSourceField dataSourceField : fields) {
addField(dataSourceField);
}
}
protected abstract OperationBinding getFetch();
protected abstract OperationBinding getRemove();
protected abstract OperationBinding getAdd();
protected abstract OperationBinding getUpdate();
public abstract String getUpdateDataURL();
public abstract String getRemoveDataURL();
public abstract String getAddDataURL();
public abstract String getFetchDataURL();
}
The class PatientDataSource that extends SpringJSONDataSource
public class PatientDataSource extends SpringJSONDataSource {
public PatientDataSource(List<DataSourceField> fields) {
super(fields);
setPrettyPrintJSON(true);
}
#Override
protected OperationBinding getFetch() {
OperationBinding fetch = new OperationBinding();
fetch.setOperationType(DSOperationType.FETCH);
fetch.setDataProtocol(DSProtocol.POSTMESSAGE);
DSRequest fetchProps = new DSRequest();
fetchProps.setHttpMethod(httpMethod.toString());
fetch.setRequestProperties(fetchProps);
return fetch;
}
#Override
public String getFetchDataURL() {
return "/spring/fetchPatients";
}
#Override
protected OperationBinding getRemove() {
return null;
}
#Override
public String getRemoveDataURL() {
return null;
}
#Override
protected OperationBinding getAdd() {
return null;
}
#Override
public String getAddDataURL() {
return null;
}
#Override
protected OperationBinding getUpdate() {
return null;
}
#Override
public String getUpdateDataURL() {
return null;
}
}
My spring controller PatientControler
#Controller
public class PatienController {
Logger logger = Logger.getLogger(PatienController.class);
#Autowired
private PatientServices patientServices;
#RequestMapping(value = "/patientTest", method = RequestMethod.GET)
#ResponseBody
public Object getTest()
{
return patientServices.getAllPatients();
}
#RequestMapping(value = "/fetchPatients", method = RequestMethod.POST)
#ResponseBody
public Object getAllPatients()
{
return patientServices.getAllPatients();
}
}
PatientServiceImpl
public class PatientServicesImpl implements PatientServices {
public List<Patient> getAllPatients() {
List<Patient> patients = new ArrayList<Patient>();
Patient patient;
for(int i = 0 ; i < 500 ; i++){
patient = new Patient();
patient.setDateOfBirth(new Date());
patient.setFirstName("Joe");
patient.setMiddleName("Moe");
patient.setLastName("Blow");
patient.setLastConsultation(new Date());
patient.setSex(Sex.M);
patients.add(patient);
}
return patients;
}
}
*Im Really stuck right now i've been looking for all type of answers .... but so far nothing worked when i tried to override the transformResponse from my RestDataSource impentation the parameter "data" as an OBJECT, returns me an array [object Object],[object Object],[object Object],[object Object],[object Object] *
The Data which is transferred from the RestDataSource has a specific format which is described in the JavaDoc of the RestDataSource
Your server must understand the request and send back a valid response.
At the moment your example doesn't seem to honour the contract.
To debug the traffic send to and from your server you can use the SmartClient-Console. You can open it by a browser bookmark like this:
javascript:isc.showConsole()
Of cause you need to deploy this console by adding the following module to your gwt.xml
<inherits name="com.smartclient.tools.SmartClientTools"/>
Now go to the RPC Tab and check Track-RPCs

Resources