How to get the body from a POST call. JAX-RS - java

I make a POST-type call in eclipse / java using JAX-RS
I can not handle the return in the method predictCid
This method sends the textToPredict parameter and receives a return string, how can I get this value and set it to the variable, textPredicted?
#Path("Predicao")
public class PredicaoCIDResource extends BaseResource {
#POST
#Path("predicaoCid")
public RetornoGenerico<PredicaoCidVo> predizerCid(PredicaoCidVo predicaoVo) {
System.out.print("\nentrou no método java");
RetornoGenerico<PredicaoCidVo> retorno = new RetornoGenerico<PredicaoCidVo>();
String nomeMetodo = "predicaoCid";
super.criarRetornoSucesso(nomeMetodo, retorno);
System.out.print("passou pelo super");
try {
System.out.print("\nentrou no try");
PredicaoCidVo predicaoCidVo = new PredicaoCidVo();
Response retornoPred = predictCid(predicaoVo.getTextToPredict());
System.out.print("retornou do método predict");
predicaoCidVo.setTextPredicted(retornoPred.getEntity().toString());
retorno.setRetorno(predicaoCidVo);
} catch (Exception e) {
super.trataExececao(retorno, e, nomeMetodo);
}
return retorno;
}
#POST
#Path("http://127.0.0.1:5000/predict")
#Consumes("application/x-www-form-urlencoded")
private Response predictCid(#FormParam("textToPredict") String predicaoVo) throws IOException {
System.out.print("\nentrou no método predict");
//How get te return ??? String
}
PredicaoVo:
#XmlRootElement
public class PredicaoCidVo implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2471424108047814793L;
private String textToPredict;
private String textPredicted;
public String getTextToPredict() {
return textToPredict;
}
public void setTextToPredict(String textToPredict) {
this.textToPredict = textToPredict;
}
public String getTextPredicted() {
return textPredicted;
}
public void setTextPredicted(String textPredicted) {
this.textPredicted = textPredicted;
}
}
The call is made correctly (predictCid), returns with status 200 (OK).
But, I can not return in one of the class variables PredicaoVo.
How do I make this return by filling in, for example, the textPredicted object?
The return, within the method that does the POST, is a simple string
Below, the feedback I have on SOAPUI testing:
<Response xmlns="http://app-homolog/overcare-ws/rest/Profissional/predicaoCid">
<retorno>
<textPredicted>predicao.PredicaoCidVo#3372c9d7</textPredicted>
<textToPredict null="true"/>
</retorno>
<retornoMensagem>
<dsMensagem>predicaoCid.sucesso</dsMensagem>
<dsStackTrace null="true"/>
<dsTitulo>predicaoCid.titulo</dsTitulo>
<idCamada>SUCESSO</idCamada>
</retornoMensagem>
</Response>
Who sends the return to the soapUI is the method predizerCid

Related

Jersey JSON to object conversion using MOXY not working

I am learning the jersey #POST REST call for a simple method which takes in json and returns a simple text. I am using MOXY with Jersey.
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.28</version>
</dependency>
My method looks as follows:
#Path("/travel")
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.TEXT_PLAIN)
public String testServletPost(ThingsToSeeInParis thingsToSeeInParis)
{
if (thingsToSeeInParis != null){
System.out.println("thingsToSeeInParis.isSeenEiffeltower() "+thingsToSeeInParis.isSeenEiffeltower());
System.out.println("thingsToSeeInParis.isSeenLouvre() "+thingsToSeeInParis.isSeenLouvre());
System.out.println("thingsToSeeInParis.isSeenMontMaetre() "+thingsToSeeInParis.isSeenMontMaetre());
System.out.println("thingsToSeeInParis.id "+thingsToSeeInParis.getId());
}
if (thingsToSeeInParis.isSeenEiffeltower() && thingsToSeeInParis.isSeenLouvre()){
System.out.println("Please shut up the lady behind me");
return "OK";
}
else{
System.out.println("Its a lost case!");
return "Not OK";
}
}
My ThingsToSeeInParis class is simple POJO class. Looks as follows:
public class ThingsToSeeInParis {
private boolean seenEiffeltower;
private boolean seenMontMaetre;
private boolean seenLouvre;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isSeenEiffeltower() {
return seenEiffeltower;
}
public void setSeenEiffeltower(boolean seenEiffeltower) {
this.seenEiffeltower = seenEiffeltower;
}
public boolean isSeenMontMaetre() {
return seenMontMaetre;
}
public void setSeenMontMaetre(boolean seenMontMaetre) {
this.seenMontMaetre = seenMontMaetre;
}
public boolean isSeenLouvre() {
return seenLouvre;
}
public void setSeenLouvre(boolean seenLouvre) {
this.seenLouvre = seenLouvre;
}
}
When I call this method from POSTMAN I get 200 response code but it always returns "Not OK". My postman calls are as follows:
No matter what or how many inputs I put I always get the same output. MOXY is just initializing all the values to default and that is why evaluation is not working. Can someone spot the issue in this code? Please let me know. Thank you.

Why an ejb that has another ejb as a field doesn´t update the values of this ejb that is acting as a field?

I am making my first approach to java-ee. What I am trying to achieve is next:
I have written an application that collects bets prices from differents sources, I manage the collected data into a custom List class(ListEventsArquitectura) that manages the events data stored in EventoArquitectura(custom class). This EventoArquitectura class has also as fields other custom objects like BetArquitectura.
What I am testing is that this application works as a client of an Ejb sending the collected data to have it available later as a Rest webservice of the Ejb.
Now I have an ejb remote interface to modify fields of EventoArquitectura instances contained into ListEventsArquitectura, and it works but as EventoArquitectura instances have as a field instances of BetArquitectura I also created another Ejb remote interface to modify the fields of BetArquitectura and here is where I have the problem because the updates of the field BetArquitectura contained into EventoArquitectura doesn't produce any change.
I leave my code of the classes created for the tests and for the remote client.
For clarification, I am not using #Inject because it produces errors deploying to glassfish so I change the annotation to #Ejb.
#Stateful
public class ListEventsArquitectura implements ListEventsArquitecturaService{
List<EventoArquitectura> listaDeEventos;
#Ejb
private EventoArquitectura eventoService;
public ListEventsArquitectura() {
this.listaDeEventos = new ArrayList<>();
List<BetArquitectura> betsList = new ArrayList<>();
//betsList.add(new BetArquitectura("betDelConstructor", "0"));
this.listaDeEventos.add(new EventoArquitectura("evento del contructor id", "betIdDelConstructor"));
}
public List<EventoArquitectura> getListaDeEventos() {
return listaDeEventos;
}
#Override
public void updateListEvent(EventoArquitectura eventoActualizado){
for(EventoArquitectura evento : this.listaDeEventos){
if(evento.equals(eventoActualizado)){
this.eventoService = evento;
eventoService.updateEvent(eventoActualizado);
return;
}
}
}
#Override
public EventoArquitectura getEventFromList(int index) {
return this.listaDeEventos.get(index);
}
#Override
public void addEvent(EventoArquitectura evento) {
this.listaDeEventos.add(evento);
}
}
public interface ListEventsArquitecturaService {
public void updateListEvent(EventoArquitectura updatedEvent);
public EventoArquitectura getEventFromList(int index);
public void addEvent(EventoArquitectura evento);
}
#Stateful
public class EventoArquitectura implements Serializable,EventoArquitecturaService {
String eventId;
// List<BetArquitectura> betsList;
String betId;
public EventoArquitectura() {
}
public EventoArquitectura(String eventId, String betId) {
this.eventId = eventId;
//this.betsList = betsList;
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
/* public List<BetArquitectura> getBetsList() {
return betsList;
}
public void setBetsList(List<BetArquitectura> betsList) {
this.betsList = betsList;
}
*/
public String getBetId() {
return betId;
}
public void setBetId(String betId) {
this.betId = betId;
}
#Override
public void updateEvent(EventoArquitectura updatedEvent){
if(!(updatedEvent.equals(this))){
this.eventId = updatedEvent.eventId;
}
}
#Override
public boolean equals(Object obj) {
if(!(obj instanceof EventoArquitectura)){
return false;
}
EventoArquitectura evento = (EventoArquitectura)obj;
return evento.eventId.equals(this.eventId);
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + Objects.hashCode(this.eventId);
return hash;
}
}
#Remote
public interface EventoArquitecturaService {
public void updateEvent(EventoArquitectura updatedEvent);
public String getBetId();
public void setBetId(String betId);
}
public class BetArquitectura implements Serializable{
String marketId;
String valorBet;
public BetArquitectura(String marketId, String valorBet) {
this.marketId = marketId;
this.valorBet = valorBet;
}
public BetArquitectura() {
}
public String getMarketId() {
return marketId;
}
public void setMarketId(String marketId) {
this.marketId = marketId;
}
public String getValorBet() {
return valorBet;
}
public void setValorBet(String valorBet) {
this.valorBet = valorBet;
}
private void updateValor(String valorBet){
this.valorBet = valorBet;
}
public void updateBet(BetArquitectura betActualizada){
if(this.equals(betActualizada)){
this.updateValor(betActualizada.getValorBet());
}
}
#Override
public boolean equals(Object obj) {
if(!(obj instanceof BetArquitectura)){
return false;
}
BetArquitectura bet = (BetArquitectura)obj;
return bet.marketId.equals(this.marketId);
}
#Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + Objects.hashCode(this.marketId);
return hash;
}
}
And here I leave my remote client, It can change values of fields of the instances of EventoArquitectura contained in the ListEventsArquitectura, but if It doesn´t make changes into BetArquitectura object contained into each EventoArquitectura instance.
public class ClienteArquitecturaTest {
public static void main(String[] args){
try {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
// optional. Default localhost. Aquise cambia la IP del servidor donde esta Glassfishprops.setProperty("org.omg.CORBA.ORBInitialHost", "127.0.0.1");
// optional. Puerto por Default 3700. Solo se necesita cambiar si el puerto no es 3700.
//props.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
Context jndi;
jndi = new InitialContext(props);
ListEventsArquitecturaService listEventsService = (ListEventsArquitecturaService) jndi.lookup("java:global/ArquitecturaEJBTest/ListEventsArquitectura!com.mycompany.ejb.interfaces.ListEventsArquitecturaService");
System.out.println("Id of the event added into constructor: " + listEventsService.getEventFromList(0).getEventId());
EventoArquitecturaService eventoParaModificar = listEventsService.getEventFromList(0);
eventoParaModificar.setBetId("betIdModified");
listEventsService.addEvent(new EventoArquitectura("newEventId", "newBetId"));
System.out.println("Modified Bet Id: " + listEventsService.getEventFromList(0).getBetId());
System.out.println("Added EventoArquitectura id: " + listEventsService.getEventFromList(1).getEventId());
System.out.println("Added Bet Id: " + listEventsService.getEventFromList(1).getBetId());
} catch (NamingException ex) {
Logger.getLogger(ClienteArquitecturaTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
And the output I get with this client, shows that I didn´t achieve to modify BetArquitectura objects, they are always null:
Id of the event added into constructor: evento del contructor id
Modified Bet Id: null
Added EventoArquitectura id: newEventId
Added Bet Id: null
I think your problem is that you modifiy an property of an instance which does only exists on the client side. When you call a method via a EJB client proxy, which returns an object, then you get an own instance (serialized on server side and deserialized at client side). These are two different objects, one exists on the client side and the other on the server side. Thats a common misunderstanding when working with remote ejbs.
Try to implement a method on your EJB like this, which modifies the intended object property on ther server side.
setIdAt(Integer idx, String id)
Then implement on the client side
// will pass parameters to server side EJB, which modifies the object property
service.setIdAt(0, "betIdModified");
// Get server side modified instance and its id
service.getElementFromList(0).getBetId();
With the example you pass parameters to the server side EJB and and the object on the server side gets modfied, which you retrieve after the server side EJB has modified it. Again, you get your own instance, which is not a proxy, as I assume you expect it to be. Only the service is proxied not the objects its methods return.

How to remove try/catch repetitions in class methods?

I have RESTeasy service. And have implemented simple error handling on methods using try catch and feel something is not very well with it. I've noticed try catch repetition on all my methods. So I want ask way how to avoid repetition (to reduce code size) of try catch but not lost functionality.
#Path("/rest")
#Logged
#Produces("application/json")
public class CounterRestService {
#POST
#Path("/create")
public CounterResponce create(#QueryParam("name") String name) {
try {
CounterService.getInstance().put(name);
return new CounterResponce();
} catch (Exception e){
return new CounterResponce("error", e.getMessage());
}
}
#POST
#Path("/insert")
public CounterResponce create(Counter counter) {
try {
CounterService.getInstance().put(counter);
return new CounterResponce();
} catch (Exception e){
return new CounterResponce("error", e.getMessage());
}
}
#DELETE
#Path("/delete")
public CounterResponce delete(#QueryParam("name") String name) {
try {
CounterService.getInstance().remove(name);
return new CounterResponce();
} catch (Exception e){
return new CounterResponce("error", e.getMessage());
}
}
... // other methods with some try catch pattern
response
public class CounterResponce {
private String status;
#JsonSerialize(include=Inclusion.NON_NULL)
private Object data;
public CounterResponce() {
this.status = "ok";
}
public CounterResponce(Object o) {
this.status = "ok";
this.data = o;
}
public CounterResponce(String status, Object o){
this.status = status;
this.data = o;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
exceptions source
public class CounterService {
private Map<String, StatisticCounter> counters = new HashMap<String, StatisticCounter>();
private static CounterService instance = null;
protected CounterService() {}
public static CounterService getInstance() {
if(instance == null) {
instance = new CounterService();
}
return instance;
}
public StatisticCounter get(String name){
StatisticCounter c = counters.get(name);
if(c == null)throw new IllegalArgumentException("Counter "+name+" not exist");
return c;
}
public void put(String name){
if(name==null)throw new IllegalArgumentException("null can`t be as name");
if(counters.get(name)!=null)throw new IllegalArgumentException("Counter "+name+" exist");
counters.put(name, new Counter(name));
}...
The comments in your question are pointing you in a good direction. Since the answers do not mention it, I'll summarize the general idea in this answer.
Extending WebApplicationException
JAX-RS allows to define direct mapping of Java exceptions to HTTP error responses. By extending WebApplicationException, you can create application specific exceptions that build a HTTP response with the status code and an optional message as the body of the response.
The following exception builds a HTTP response with the 404 status code:
public class CustomerNotFoundException extends WebApplicationException {
/**
* Create a HTTP 404 (Not Found) exception.
*/
public CustomerNotFoundException() {
super(Responses.notFound().build());
}
/**
* Create a HTTP 404 (Not Found) exception.
* #param message the String that is the entity of the 404 response.
*/
public CustomerNotFoundException(String message) {
super(Response.status(Responses.NOT_FOUND).
entity(message).type("text/plain").build());
}
}
WebApplicationException is a RuntimeException and doesn't need to the wrapped in a try-catch block or be declared in a throws clause:
#Path("customers/{customerId}")
public Customer findCustomer(#PathParam("customerId") Long customerId) {
Customer customer = customerService.find(customerId);
if (customer == null) {
throw new CustomerNotFoundException("Customer not found with ID " + customerId);
}
return customer;
}
Creating ExceptionMappers
In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response.
For such cases it is possible to use a custom exception mapping provider. The provider must implement the ExceptionMapper<E extends Throwable> interface. For example, the following maps the JAP EntityNotFoundException to a HTTP 404 response:
#Provider
public class EntityNotFoundExceptionMapper
implements ExceptionMapper<EntityNotFoundException> {
#Override
public Response toResponse(EntityNotFoundException ex) {
return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
}
}
When an EntityNotFoundException is thrown, the toResponse(E) method of the EntityNotFoundExceptionMapper instance will be invoked.
The #Provider annotation declares that the class is of interest to the JAX-RS runtime. Such class may be added to the set of classes of the Application instance that is configured.
Introduce a private method such as "apply" which can take function as parameter if you use Java 8. This method will have the error handling and/or mapping, response mapping and response generation code centralized.
From create and delete methods, invoke this apply method and pass the desired counter operation you wish to perform as a lambda expression.

Java, Storing JSON Array to class and calling it from other class

I am trying to pull data from class in another class and populate a JPanel with the data, but it is not working for some reason.
Here is the full restConnector class where I pull the JSON data.
As far as I know this works fine.
public class restConnector {
private static final Logger LOGGER = LoggerFactory.getLogger(restConnector.class);
private static final restConnector INSTANCE = new restConnector();
public static restConnector getInstance() {
return restConnector.INSTANCE;
}
private restConnector(){
}
private static String user = "ss";
private static String pwd = "ee
public static String encode(String user, String pwd) {
final String credentials = user+":"+pwd;
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(credentials.getBytes());
}
//Open REST connection
public static void init() {
restConnector.LOGGER.info("Starting REST connection...");
try {
Client client = Client.create();
client.addFilter(new LoggingFilter(System.out));
WebResource webResource = client.resource("https://somewebpage.com/
String url = "activepersonal";
ClientResponse response = webResource
.path("api/alerts/")
.queryParam("filter", ""+url)
.header("Authorization", "Basic "+encode(user, pwd))
.header("x-api-version", "1")
.accept("Application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
}else{
restConnector.LOGGER.info("REST connection STARTED.");
}
String output = response.getEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setPropertyNamingStrategy(new MyNameStrategy());
try {
List<Alert> alert = mapper.readValue(output, new TypeReference<List<Alert>>(){});
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
}
}
However, when I try to pull the data in another class it gives me just null values from the system.out.print inside refreshData() method. Here is the code that is supposed to print the data
public class Application{
Alert alerts = new Alert();
public Application() {
refreshData();
}
private void initComponents() {
restConnector.init();
refreshData();
}
private void refreshData() {
System.out.println("appalertList: "+alerts.getComponentAt(0));
}
}
Here is my Alert class
#JsonIgnoreProperties(ignoreUnknown = true)
#JsonInclude(Include.NON_EMPTY)
public class Alert {
private int pasID;
private String status;
private boolean shared;
private String header;
private String desc;
public int getPasID() {
return pasID;
}
public void setPasID(int pasID) {
this.pasID = pasID;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\n***** Alert Details *****\n");
sb.append("PasID="+getPasID()+"\n");
sb.append("Status="+getStatus()+"\n");
sb.append("Shared="+isShared()+"\n");
sb.append("Header="+getHeader()+"\n");
sb.append("Description="+getDesc()+"\n");
sb.append("*****************************");
return sb.toString();
}
public String getComponentAt(int i) {
return toString();
}
}
I'm kind a lost with this and been stuck here for a couple of days already so all help would be really appreciated. Thanks for the help in advance.
Edit: Formatted the code a bit and removed the NullPointerException as it was not happening anymore.
As stated in comments:
Me: In your first bit of code you have this try { List<Alert> alert.., but you do absolutely nothing with the newly declared alert List<Alert>. It this where the data is supposed to be coming from?
OP: I'm under the impression that that bit of code is the one that pushes the JSON Array to the Alert.class. Is there something I'm missing there?
Me: And what makes you think it does that? All it does is read the json, and the Alert.class argument is the class type argument, so the mapper know the results should be mapped to the Alert attributes when it creates the Alert objects. That's how doing List<Alert> is possible, because passing Alert.class decribes T in List<T>. The List<Alert> is what's returned from the reading, but you have to determine what to actually do with the list. And currently, you do absolutely nothing with it
You maybe want to change the class just a bit.
Now this is in no way a good design, just an example of how you can get it to work. I would take some time to sit and think about how you want the restConnector to be fully utilized
That being said, you can have a List<Alert> alerts; class member in the restConnector class. And have a getter for it
public class restConnector {
private List<Alert> alerts;
public List<Alert> getAlerts() {
return alerts;
}
...
}
Then when deserializing with the mapper, assign the value to private List<Alert> alerts. What you are doing is declaring a new locally scoped list. So instead of
try {
List<Alert> alert = mapper.readValue...
do this instead
try {
alerts = mapper.readValue
Now the class member is assigned a value. So in the Application class you can do something like
public class Application {
List<Alert> alerts;
restConnector connect;
public Application() {
initComponents();
}
private void initComponents() {
connector = restConnector.getInstance();
connector.init();
alerts = connector.getAlerts();
refreshData();
}
private void refreshData() {
StringBuilder sb = new StringBuilder();
for (Alert alert : alerts) {
sb.append(alert.toString()).append("\n");
}
System.out.println("appalertList: "+ sb.toString());
}
}
Now you have access to the Alerts in the list.
But let me reiterate: THIS IS A HORRIBLE DESIGN. For one you are limiting the init method to one single call, in which it is only able to obtain one and only one resource. What if the rest service needs to access a different resource? You have made the request set in stone, so you cant.
Take some time to think of some good OOP designs where the class can be used for different scenarios.

Rest Easy Client Framework value lost after unmarshaling

Yesterday I tried to use the client side of the RestEasy framework. The interface has a method:
#PUT
#Path("document/autoincrement")
#Consumes("application/xml")
BaseClientResponse<String> insertPointOfInterest(PoiDocument poiDocument);
and the call to some (Jersey) rest service looks like:
String restServerServiceUrl = "http://my.jersey.server/rest/serviceFoo/v1/";
NSSClientService client = ProxyFactory.create(NSSClientService.class, restServerServiceUrl);
PoiDocument poiDocument = new PoiDocument("Parkirišče", "90", 390262.85133115170, 42240.33558245482);
BaseClientResponse<String> response = client.insertPointOfInterest(poiDocument);
assert response.getResponseStatus() == Response.Status.OK;
// Expected result
//<?xml version="1.0" encoding="UTF-8" standalone="yes"?><insertedRecord><record>14</record></insertedRecord>
logger.info("Returned: " + response.getEntity());
And the logger prints:
14
Kind of expected.
But I want an object not a string, so I can easely assert the values returned. The interface:
#PUT
#Path("document/autoincrement")
#Consumes("application/xml")
BaseClientResponse<InsertedResponse> insertPointOfInterest(PoiDocument poiDocument);
Instead of String there is now a InsertedResponse class which looks like:
#XmlRootElement(name="insertedRecord")
public class InsertedResponse extends ResponseResult{
String insertedRecord;
public InsertedResponse(int insertedRecord) {
this.insertedRecord = Integer.toString(insertedRecord);
}
public InsertedResponse(){
insertedRecord = "";
}
#XmlElement(name="record")
public String getInsertedRecords(){
return insertedRecord;
}
public void add(int recNo) {
insertedRecord = Integer.toString(recNo);
}
}
...and its superclass:
#XmlRootElement(name = "result")
public abstract class ResponseResult {
protected String getClearString(String string) {
if (string != null) {
return Constants.removeInvalidXMLCharacters(string);
}
return "";
}
}
Now, when I change the client call also to:
BaseClientResponse<InsertedResponse> response = client.insertPointOfInterest(poiDocument);
logger.info("Returned: " + response.getEntity().getInsertedRecords());
I get an empty string instead of some value.
So, the question is - where did the value of go? It should print a number, like 14 in the above example.
One missing JAXB annotation (#XmlSeeAlso)
#XmlRootElement(name = "result")
#XmlSeeAlso( { InsertedResponse.class, OtherChild.class, SomeOtherChild.class })
public abstract class ResponseResult {
...
}
and an added setter method
#XmlRootElement(name="insertedRecord")
public class InsertedResponse extends ResponseResult{
...
public void setInsertedRecords(String insertedRecord) {
this.insertedRecord = insertedRecord;
}
solved the problem.

Categories

Resources