Java REST WebService - java

I'm trying to build a Java REST web service that will do some processing on a get request (eg. send get request with info, do some calculations, then send back an object with the results). Any ideas how I can set this up easily in Netbeans? I've been playing with the New->RESTful web service... feature, but can't seem to get it to return an object.

AFAIK you're supposed to return a string representation of the result. For example implementing the getXml() method:
/**
* Retrieves representation of an instance of services.GenericResource
* #return an instance of java.lang.String
*/
#GET
#Produces("application/xml")
public String getXml() {
return "<entry></entry>";
}
You could use an XML API to turn your objects into XML strings and return them.

What kind of object do you want to return...?
In java rest webservice you can return many kinds of objects like json,xml.
You can follow these tutorials for creating any kind of java rest webservice -
http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
This link shows example of get request which returns a json object. You can browse there tutorials for any other requirements.

I haven't tried it in Netbeans, but I have done it using Intellij tho, using maven. Just used servlets to get the requests and used GSON to convert the outgoing java object to JSON and send it out.
This is the project I did with some of my colleges.

Related

Mule Anypoint Studio Passing in JSON and working in Java

I'm not too familiar with Anypoint and we will probably only use this program once, I've looked at tutorials on the website but I feel I can't find one that demonstrates the task we have. Basically we are trying to read a JSON file that will be sent to the software, from there we want to use JAVA to read/alter the contents into a desired XML formatting. Finally we then send back or redirect the XML results.
1: I am trying to accept a JSON file from a HTTP POST, I believe I have accomplished this part by using the tutorials and an HTTP element with metadata attached representing the JSON format that may come. Using postman to send the json data as well.
2: From here is where I start to get completely confused. I am wondering what I would need to do in order to pass the data into a Java class object to read the JSON file and begin using Java code (getters/setters) instead of the Anypoint interface in order to start designing the xml layout.
Thanks,
I think the next step is for you to define a model class(with getter/setter), which would represent your json file contents. Since you have already the POST part, the next thing you would do is to use JSON to Object Transformer which the model is injected in.
<json:json-to-object-transformer returnClass="com.alexfrndz.Person" doc:name="JSON to Object"/>
After adding the transformer, you could use a mule custom transformer,
Here is the custom transformer.
package com.alexfrndz;
import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.transformer.AbstractMessageTransformer;
public class PersonTransformer extends AbstractMessageTransformer {
#Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
Person person = (Person) message.getPayload();
//Do your transformation hear
return null;
}
}
Here is how you implement it,
<custom-transformer class="com.alexfrndz.PersonTransformer" doc:name="PersonTransformer"/>
Hope this will help you.

Converting JSON to Java Object in RESTful app [duplicate]

I have to integrate our j2ee application with a REST webservice. And I wanted to use the RestEasy JAX-RS implementation from JBoss. The webservice returns an array in JSON format. I've this piece of code:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://myservices.com/schemes/all");
Response response = target.request().get();
Can I map this "response" object to List<Scheme> using RestEasy? Thanks
Provided that your JSON provider is capable of converting JSON to appropriate entities, then yes. The get method you call in the code has an overloaded version which accepts the class of entity to which the result is to be converted. Since there are problems with serializing certain collections' implementations, your type has to be wrapped in GenericType class, like that:
List<Scheme> schema = [...].get(new GenericType<List<Scheme>>(){});
The above method should work with just about every JAX-RS-compliant implementation.
You can also use Jackson library, which allows you (amongst other things) to pass collections without need of wrapping them.

Response from Web Service in Glassfish from C# client

I'm having a problem where my C# client can't parse the data from my webservice in Glassfish.
I have a WSDL and XSD for my webservices as follows:
http://www.consorciovivedigital.com:8080/ServicioInterventoria/ServicioInterventoria?WSDL
http://www.consorciovivedigital.com:8080/ServicioInterventoria/ServicioInterventoria?xsd=1
And I'm using the next C# client to test this webservice:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ServicioInterventoria;
public partial class _Default : System.Web.UI.Page
{
ServicioInterventoria.ServicioInterventoria proxy;
protected void Page_Load(object sender, EventArgs e)
{
proxy = new ServicioInterventoria.ServicioInterventoria();
ResultadoMensualIC[] res = proxy.ObtenerResultadosMensuales("Intv12", "2014-07-07T08:08:08");
System.Diagnostics.Debug.WriteLine(res.Length);
System.Diagnostics.Debug.WriteLine(res[0].FechaCorte);
}
}
The problem is that when I execute this code, the res array has the amount of objects that should have, but each value of each object has the default value instead of the correct value. I used Fiddler to check the traffic and it receives the correct SOAP response with the correct data, but it seems that my C# client doesn't know how to parse the data.
I checked with a Java client, and I can get the correct data without any problems, and seems that my C# it's the only one giving problems with this.
Maybe there is a problem with the targetNamespace in the SOAP response, but I don't understand why works correctly in Java but in C# just puts default values.
Anyone have any idea what could be the problem?
If someone needs more information about it, let me know
Thanks beforehand
I solved last week. The problem was that the SOAP response didn't put the namespace for each attribute, then, the C# client doesn't know how to match this (seems like a limitation of C#). And, the other problem was the order of the SOAP response, because, the C# client was expecting each object as was defined in the WSDL, but the response it's ordered alphabetically, in this way, the C# client, doesn't match correctly each attribute.
I did some modifications to the client. First, in each model, for each attribute I added the namespace, something like this:
#XmlElement(name = "IdInterventor", namespace = "http://ws.bigdatasolutions.co/")
public String getIdInterventor() {
return IdInterventor;
}
With this, the SOAP response always puts the namespace for each attribute, which was neccesary for the C# client.
After that, at the beginning of each model class I add this tag, to define the order as defined in the WSDL and expected for the C# client.
#XmlRootElement(name = "AspectosFinancieros")
#XmlType(propOrder={"idInterventor", "numeroContrato", "ano", "valorContratoOperador", "fechaFirmaContrato",
"valorAdicion", "fechaProrrogaAdicion", "valorDesembolso", "fechaPagoDesembolso",
"valorAnticipo", "fechaAnticipo", "valorUtilizacion", "numeroActaAprobacion",
"fechaUtilizacion", "valorRendimiento", "fechaRendimiento", "numeroComprobanteRendimiento",
"valorComision", "fechaComision", "valorGastosAdministrativos", "fechaGastosAdministrativos",
"nombreFiducia", "numeroContratoFiducia", "fechaContratoFiducia", "fechaProrrogaAdicionFiducia",
"marcaTiempo"})
public class AspectosFinancieros {
I checked the expected order in the auto generated class in the C# client.
I hope someone find this useful.

Retrieve hashmap values from java servlet to flex

I am working on "migration from JSP to FLEX, and java as back-end. I am novice in java and JSP.
I am stuck at getting values from a java servlet where it takes httprequest and there is a function called forward(request,response) which responds as JSP page with requried values in it.
Now I need to change that and get only data from that servlet and use that in flex.
Problem:
case1: When using httpservice it takes result as string, but unable to get as object.
case2: If I use RemoteObject , it needs method in java servlet to get return value, which is not present in existing servlet.
Can I get any suggestions on this problem.
Thank You
case1: you don't use forward anymore, you set the type of data you want to return, for example:
response.setContentType("application/json");
... and returning data in servlet is done by writing data to a stream like:
PrintWriter out = response.getWriter();
out.print(object);
but it's a while ago since I did this, so there may be some small problem you will face...
case2: if you are using servlet, it's correct to use HTTPService, RemoteObject will not work, it is used differently....
Now, if I can, I would suggest diferent thing to use than servlets - to obtain data from a java server to Flex - I love to use GraniteDS.
I will just state some benefits I see, in case you are interested:
It is easy to setup:
- in java, you will just add a graniteDS library, two config files (granite+services-config xmls) add a granite servlet config to web.xml
- in flex there is also granite library and services-config.xml
When set up, using it is also flowleslly easy - you have a class with a method (or simple bean or ejb) in Java which just return an object of any type! And that's it in Java
In flex, in this case you use RemoteObject which you just call that remote java method and in result handler you get your dataGranite will take care of serializing+transfer+deserializing and just give you the Object (either just dynamic {} or even exact class type)

Google App Engine class on client side

I am developing an Android app using GAE on Eclipse.
On one of the EndPoint classes I have a method which returns a "Bla"-type object:
public Bla foo()
{
return new Bla();
}
This "Bla" object holds a "Bla2"-type object:
public class Bla {
private Bla2 bla = new Bla2();
public Bla2 getBla() {
return bla;
}
public void setBla(Bla2 bla) {
this.bla = bla;
}
}
Now, my problem is I cant access the "Bla2" class from the client side. (Even the method "getBla()" doesn't exist)
I managed to trick it by creating a second method on the EndPoint class which return a "Bla2" object:
public Bla2 foo2()
{
return new Bla2();
}
Now I can use the "Bla2" class on the client side, but the "Bla.getBla()" method still doesn't exit. Is there a right way to do it?
This isn't the 'right' way, but keep in mind that just because you are using endpoints, you don't have to stick to the endpoints way of doing things for all of your entities.
Like you, I'm using GAE/J and cloud endpoints and have an ANdroid client. It's great running Java on both the client and the server because I can share code between all my projects.
Some of my entities are communicated and shared the normal 'endpoints way', as you are doing. But for other entities I still use JSON, but just stick them in a string, send them through a generic endpoint, and deserialize them on the other side, which is easy because the entity class is in the shared code.
This allows me to send 50 different entity types through a single endpoint, and it makes it easy for me to customize the JSON serializing/deserializing for those entities.
Of course, this solution gets you in trouble if decide to add an iOS or Web (unless you use GWT) client, but maybe that isn't important to you.
(edit - added some impl. detail)
Serializing your java objects (or entities) to/from JSON is very easy, but the details depend on the JSON library you use. Endpoints can use either Jackson or GSON on the client. But for my own JSON'ing I used json.org which is built-into Android and was easy to download and add to my GAE project.
Here's a tutorial that someone just published:
http://www.survivingwithandroid.com/2013/10/android-json-tutorial-create-and-parse.html
Then I added an endpoint like this:
#ApiMethod(name = "sendData")
public void sendData( #Named("clientId") String clientId, String jsonObject )
(or something with a class that includes a List of String's so you can send multiple entities in one request.)
And put an element into your JSON which tells the server which entity the JSON should be de serialized into.
Try using #ApiResourceProperty on the field.

Categories