I am working on one project in which i am developing a java client for .NET/C#.
I want to send information of device to the web service.
I have created one class which contains the device information.
I want to send the information of the device to service.
what is appropriate way to do this. Please help.
sorry for my weak English.
And thanks in advance.
package com.ivb.syntecApp.models;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class DeviceInformation {
private String vendorId;
private String productId;
private String hardwareRevision;
private String deviceName;
private String manufacturerName;
#XmlElement
public String getVendorId() {
return vendorId;
}
public void setVendorId(String vendorId) {
this.vendorId = vendorId;
}
#XmlElement
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#XmlElement
public String getHardwareRevision() {
return hardwareRevision;
}
public void setHardwareRevision(String hardwareRevision) {
this.hardwareRevision = hardwareRevision;
}
#XmlElement
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
#XmlElement
public String getManufacturerName() {
return manufacturerName;
}
public void setManufacturerName(String manufacturerName) {
this.manufacturerName = manufacturerName;
}
}
For this purpose the Common Object Request Broker Architecture (CORBA) was developed. But it's too big gun for your needs. I recommend you to use some kind of REST or SOAP service with transformators(Adapter pattern)
I have solved at my own. I don't know is it good practice or not.
My answer is ->
I have used JAXB for marshaling DeviceInformation class and used
`void marshal(Object jaxbElement,
Writer writer)
throws JAXBException
` to convert this object in to StringWriter object then converted it into string and sent this string to .NET/C# service.
This meets my requirement.
I found this here
Related
I have created a rest api in eclipse as a maven project.
MobileAnalyticsModel class for rest api is
package org.subhayya.amazonws.mobileanalytics;
import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class MobileAnalyticsModel {
private String name;
private Date created;
private String location;
private String prize;
private String requirement;
public MobileAnalyticsModel() {
}
public MobileAnalyticsModel(String name, String location, String prize, String requirement) {
this.name = name;
this.location = location;
this.prize = prize;
this.requirement = requirement;
this.created = new Date();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPrize() {
return prize;
}
public void setPrize(String prize) {
this.prize = prize;
}
public String getRequirement() {
return requirement;
}
public void setRequirement(String requirement) {
this.requirement = requirement;
}
}
this is the json response of the created api:
and
this is my sample test code for invoking rest api:
package org.subhayya.example;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
public class SampleTestREstClient {
public static void main(String[] args) {
Client client = ClientBuilder.newClient( );
String reponse = client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
.request(MediaType.APPLICATION_JSON)
.get(String.class);
System.out.println(reponse);
}}
then i got full json response.. as
[{"created":"2017-03-30T14:36:58.56","location":"http://api.server.com","name":"Mobile Analytics","prize":"$1.00 per 1,000,000 Amazon Mobile Analytics events per month thereafter","requirement":"PutEvents"}]
But I want to have the single parameter as my output, for e.g., name, location or requirement.I am creating client invoking code also in the same maven project. So I wrote my code as below
Client client = ClientBuilder.newClient( );
MobileAnalyticsModel reponse =
client.target("http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/mobileanalyticsjson")
.request(MediaType.APPLICATION_JSON)
.get(MobileAnalyticsModel.class);
System.out.println(reponse.getName());
But I am getting exception, So I changed it to System.out.println(reponse);
) get atleast JSON response, then also getting error.
how do I get single name parameter from the JSON response? I am new to this rest api..please help me to fix this as soon as possible.thanks in advance
Your response is a string. The simplest way to access elements of your JSON-response is to convert the resonse to a Json-Object. Then you can access the fields easily by their name.
Have a look at:
How to parse JSON in Java
You can also check the below link to convert json to object.
Parse a JSON response as an object
This code works for me..
String url = "http://localhost:8080/AgentBasedCloudServiceCompositionFramework/webapi/mobileanalytics/";
String city = "mobileanalyticsjson";
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.register(JsonProcessingFeature.class).target(url);
JsonArray jsonArray = webTarget.path(city)
.request(MediaType.APPLICATION_JSON_TYPE).get(JsonArray.class);
for (JsonObject jsonObject : jsonArray.getValuesAs(JsonObject.class)) {
System.out.println(jsonObject.getString("name"));
System.out.println(jsonObject.getString("location")); }
(NOTE: I am sorry if the layout of this post isn't the best, I've
spent quite a lot of time figuring the features of this editor)
Hi, I am doing a RESTful web project and I run into a problem returning an object that contains another object (But the object inside is literally an "Object").
In my case I have a Company, Customer and Coupon resources. Each one of then contains fields, #XMLRootElement annotation in the class level, an empty constructor (along with constructors that receives the arguments) and of course, the getters and setters.
As for the service, there are annotations in the class level:
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
And the get method it's self:
#GET
#Path("/myCompany)
public Message getMyCompany(){
Message message;
try{
message = new MessageSuccess(company);
} catch(Exception e){
message = new MessageError(e.getMessage());
}
return message;
}
Now the way Message object is built, it's an abstract class (that contains the #XMLRootElement as well) it has three fields:
messageType (enum)
value (Object)
message (String)
it has all the features of the resource (getters and setters, construction, etc...)
And there are two classes that extending the Message.
they aswell have an empty constructor and parameterized one, they don't have the #XMLRootElement annotations.
Now the problem is, when ever the client does the get method, it receives a JSON object that has
messageType: 'SUCCESS'
value: 'com.publicCodes.resources.Company#6c4sad546d'
Basically it returns a toString() of the Company object.
I have no clue how to fix that.
Returning servlet's Response object is not an option due to a bad practice.
Returning the Company object it's self is as well not an option.
Thanks and waiting for your solutions!
**
EDIT for those who wanna see the actual code:
**
Here is the Message abstract class:
package com.publicCouponRest.util;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
#XmlRootElement
public abstract class Message {
private MessageResultType messageType;
private Object value;
private String message;
public Message() {
}
public Message(MessageResultType messageType, String message) {
this.messageType = messageType;
this.message = message;
}
public Message(MessageResultType messageType, Object value) {
this.messageType = messageType;
this.value = value;
}
public MessageResultType getMessageType() {
return messageType;
}
public void setMessageType(MessageResultType messageType) {
this.messageType = messageType;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
And here is MessageSuccess that extends Message:
package com.publicCouponRest.util;
public class MessageSuccess extends Message {
public MessageSuccess() {
}
public MessageSuccess(Object value) {
super(MessageResultType.SUCCESS, value);
}
}
and of course Company resource:
package com.publicCodes.resources;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import com.publicCouponRest.services.AttributeKeys;
#XmlRootElement
public class Company {
private long id;
private String compName;
private String password;
private String email;
private Map<Long, Coupon> coupons;
private CompanyStatus companyStatus;
private AttributeKeys userType = AttributeKeys.COMPANY;
public Company(long id, String compName, String password, String email, Map<Long, Coupon> coupons, CompanyStatus companyStatus) {
this(compName, password, email);
this.id = id;
this.coupons = coupons;
this.companyStatus = companyStatus;
}
public Company(String compName, String password, String email) {
super();
this.compName = compName;
this.password = password;
this.email = email;
}
public Company() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCompName() {
return compName;
}
public void setCompName(String compName) {
this.compName = compName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Map<Long, Coupon> getCoupons() {
return coupons;
}
public CompanyStatus getCompanyStatus() {
return companyStatus;
}
public void setCompanyStatus(CompanyStatus companyStatus) {
this.companyStatus = companyStatus;
}
public void setCoupons(Map<Long, Coupon> coupons) {
this.coupons = coupons;
}
public AttributeKeys getUserType() {
return userType;
}
public void setUserType(AttributeKeys userType) {
this.userType = userType;
}
}
Ok. I think that you are having too much fun with jackson:
You are trying to put 'whatever object' in a node. aren't you?
To do that you must use the annotation:
#XmlAnyElement(lax=false)
so something like:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement
public abstract class Message {
....
#XmlAnyElement(lax=false)
private Object value;
....
Should be necessary. This way you will be able to put whatever incoming XML data node in that Object (JAXB will have to know the class of that Object and that class must be annotated, but it let you manage an undetermined class)
Also (EDITED):
In the other way: Object-> XML: The problem now is that you are sending to JAXB your 'Company' object but it only sees an 'Object' because you are telling it that it's an object of type 'Object', and JAXB only know how to serialize an 'Object.class' calling to it's .toString() because Object.class hasn't got any JAXB annotation. Try returning, instead of the object, the result of this method:
(Data will be your response and clazz Company.class or whatever)
import javax.xml.bind.JAXBContext;
import javax.xml.transform.dom.DOMResult;
import org.w3c.dom.Element;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
...
public static Element marshallToElement(Object data, Class clazz) {
DOMResult res = null;
try {
JAXBContext ctx = JAXBContextManager.getInstance(clazz.getPackage().getName());
Marshaller marshaller = ctx.createMarshaller();
res = new DOMResult();
marshaller.marshal(data, res);
} catch (JAXBException e) {
LOG.error(e);
}
return ((Document)res.getNode()).getDocumentElement();
}
This way you will return a JAXBElement, which is a 'bunch of nodes' that JAXB will know how to marshall.
At this point, if it works for you, it's a good practice caching the JAXBContext, it can be do saffely (JAXBContext is thread-safe, Marshallers NO) and it's a heavy duty for JAXB to execute that:
JAXBContextManager.getInstance(clazz.getPackage().getName())
So try to do it only once for each transformation.
PS:
Try putting JAXB annotations only in final classes, I'd had problems with that (because I was using annotations in an annotated subclass... And finally is cleaner to have all annotations in the same class)
Jersey/JAX-RS 2 client
I consider you read a bit of WebTarget API, how it works and what it returns. And Also return a Response Object
And then you can change your method to this:
#GET
#Path("/myCompany)
public Response getMyCompany() {
Message message;
try {
message = new MessageSuccess(company);
return Response.status(200).entity(message).build();
} catch (Exception e) {
message = new MessageError(e.getMessage());
return Response.status(500).entity(message).build();
}
}
After that you should add this to your main method:
WebTarget target = client.target(BASE).path("myCompany");
Response response = target.request().accept(...).post(Entity.json(message));//modify this line to suit your needs
Message message = response.readEntity(Message.class);
Have tried similar thing before and I got my help from #peeskillet's answer on this stackoverflow page.
Hope it did be of Help,thank you.
Input paramter to my webservice method is an Object of Class AddSingleDocRequest. This class contains all the input fields as class instance variable with their getter and setter. I want to make some of the input fields mandatory. What is the best way to achieve this ?
Following is the code snippet:
**//webservice method
public String uploadDoc(AddSingleDocRequest request)
{
}
**//Request Class**
public class AddSingleDocRequest
{
private String sFilepath;
private String sDataClass;
public void setDataClassName(String dataClassName)
{
this.sDataClass= dataClassName;
}
public String getDataClassName() {
return sDataClass;
}
public void setFilePath(String filePath)
{
this.sFilepath=filePath;
}
public String getFilePath()
{
return sFilepath;
}
}
I want to make sFilePath parameter as mandatory.
Add the next JAX-B annotations:
#XmlType(name = "AddSingleDocRequestType", propOrder = {
"sFilepath", "sDataClass"
})
public class AddSingleDocRequest {
#XmlElement(name = "sFilepath", required = true)
private String sFilepath;
#XmlElement(name = "sDataClass", required = false)
private String sDataClass;
public void setDataClassName(String dataClassName) {
this.sDataClass = dataClassName;
}
public String getDataClassName() {
return sDataClass;
}
public void setFilePath(String filePath) {
this.sFilepath = filePath;
}
public String getFilePath() {
return sFilepath;
}
}
See more in Using JAXB to customize mapping for JAX-WS web services.
I have application separated to frontend and backend modules which communicate through restfull webservice. Unfortunately, something goes wrong in this code and I get from Backend part:
java.lang.ClassCastException: com.rrd.ecomdd.data.SharedFile cannot be cast to javax.xml.bind.JAXBElement
Frontend snippet:
#Override
public void share(Set<SharedFile> fileSet) {
apiTarget.path(ApiConstant.FILESERVICE)
.path(ApiConstant.FILESERVICE_SHARE)
.request(MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8"))
.post(Entity.entity(fileSet.toArray(new SharedFile[0]), MediaType.APPLICATION_JSON_TYPE.withCharset("UTF-8")), new GenericType<Set<SharedFile>>() {
});
}
Backend snippet
#POST
#Path(ApiConstant.FILESERVICE_SHARE)
#Produces("application/json; charset=UTF-8")
#Consumes("application/json; charset=UTF-8")
public List<SharedFile> share(SharedFile[] sharedList) {
for (SharedFile s : sharedList) {
fileService.share(s);
}
return Arrays.asList(sharedList);
}
SharedFile class:
public class SharedFile {
private Long id;
private User user;
private ManagedFile file;
private UUID uuid = UUID.randomUUID();
public SharedFile(User user, ManagedFile file) {
this.user = user;
this.file = file;
}
public SharedFile() {
}
//getters, setters, equals and hashcode below
}
Any ideas how to fix this?
Try to annotate the class and its attributes as mentioned here:
#XmlRootElement
public class SharedFile {
#XmlElement
private Long id;
#XmlElement
private User user;
#XmlElement
private ManagedFile file;
Follow this for more: http://docs.oracle.com/javaee/6/tutorial/doc/gkknj.html
I have a webservice:
#WebService()
public interface WMCService {
#WebMethod(operationName="getGroupInfoFromUserId")
#ResponseWrapper(className="wmc.web.service.BasicGroupWrapper")
#WebResult(name="basicGroup")
BasicGroup getGroupInfoFromUserId(#WebParam(name = "id") Long id);
}
#WebService(endpointInterface="wmc.web.service.WMCService", serviceName="WMCService")
public class WMCServiceImpl implements WMCService {
#Override
public BasicGroup getGroupInfoFromUserId(Long id) {
UserHelper uh = new UserHelper();
WMCUser user = uh.getById(id);
if (user != null) {
return user.getBasicGroup();
} else {
return null;
}
}
}
and I have the ResponseWrapper:
#XmlRootElement()
#XmlType(name="Group")
#XmlAccessorType(XmlAccessType.FIELD)
public class BasicGroupWrapper {
#XmlElement(name="groupName")
private String groupName;
#XmlElement(name="groupId")
private Long groupId;
#XmlTransient
private BasicGroup basicGroup;
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public Long getGroupId() {
return groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
public void setBasicGroup(BasicGroup group) {
this.groupName = group.getGroupName();
this.groupId = group.getId();
this.basicGroup = group;
}
public BasicGroup getBasicGroup() {
return basicGroup;
}
}
When I test this operation I get the following error which I can't google a solution to. Maybe you can help.
Caused by: javax.xml.bind.JAXBException: basicGroup is not a valid property on class wmc.web.service.BasicGroupWrapper
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getElementPropertyAccessor(JAXBContextImpl.java:971)
at com.sun.xml.ws.server.sei.EndpointResponseMessageBuilder$DocLit.<init>(EndpointResponseMessageBuilder.java:203)
... 34 more
#WebResult(name="basicGroup") this is not part of your WSDL since it's marked as XmlTransient:
#XmlTransient
private BasicGroup basicGroup;
So it won't be able to pick out that part of for your response.
I had the same problem when there were MS Web Service and Java client on JBoss.
I generated stub classes using wsconsume. And after that I usually deleted package-info.java because I thought that this is redundant class. After that this case reproduced.
After some time I tried to include this file (package-info.java) into project. And it solved the problem.
But when I've used Java Web Service (on JBoss) it works perfectly even without package-info class. It's very strange. Just FYI.
Following link was helpful: link