Jersey 1.18 client with jaxb - jaxb

I am trying to use Jersey 1.18 client to get xml data from rest web service and then unmarshall it using JaxB. The problem is that I don't know how to forward data straight from Jersey into JaxB and the code looks a bit hideous.
Client client = Client.create();
WebResource webResource = client.resource("http://something.com");
ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(output);
Person person = (Person) unmarshaller.unmarshal(reader);
Is there a more elegant way of doing this? I am using Jersey 1.18 because the latest version pulls a lot! of dependencies and I would like to make my "client" really light weight..

Related

Problem with Post json data on flask server

i'm setting up a flask server and i would like to do HTTP POST request with a json content-type from android application.
for my purpose i only need to get json data from different client.
one of these client is an android application and it basically do an http post in the server.
the code of android post request is :
public void SendHttp(View view){
new Thread(new Runnable() {
#Override
public void run() {
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader bufferedReader = null;
final String lte_url="http://192.168.1.8:5000/data_center/lte";
HttpPost httpPost = new HttpPost();
try {
HttpClient httpClient = new DefaultHttpClient();
URI uri = new URI("http://192.168.1.8:5000/data_center/lte");
httpPost.addHeader(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httpPost.setURI(uri);
JSONObject send_ = json_lte;
txtSend.setText(""+send_.toString(2));
StringEntity entity = new StringEntity("{"+
"\"date\":"+"\""+send_.getString("Date")+","+
"\"Ping\":"+send_.getString("Ping")+","+
"\"Download\":"+send_.getString("Download")+","+
"\"Upload\":"+send_.getString("Upload")+","+
"\"Latitude\":"+send_.getString("Latitude")+","+
"\"Longitude\":"+send_.getString("Longitude")+","+
"\"Type\":"+send_.getString("Type")+","+
"\"RsRq\":"+send_.getString("RsRq")+","+
"\"RsRp\":"+send_.getString("RsRp")+","+
"\"SINR\":"+send_.getString("SINR")+","+
"\"Bandwidth\":"+send_.getString("Bandwidth")+
"}");
txtSend.setText(entity.toString());
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
} catch (some Exeption...)}
}
}).start();
the only output of the flask server is it
Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
192.168.1.237 - - [23/Jul/2019 22:47:58] "POST /data_center/lte HTTP/1.1" 201 -
the code about the server is :
#app.route('/data_center/lte',methods=['POST'])
def post_LTE_data():
try:
data = request.get_json(force=True)
packet = {
'date': data['Date'],
'ping': data['Ping'],
'download': data['Download'],
'upload': data['Upload'],
'latitude': data['Latitude'],
'longitude': data['Longitude'],
'type': data['Type'],
'RsRq': data['RsRq'],
'RsRp': data['RsRp'],
'SINR': data['SINR'],
'bandwidth': data['Bandwidth']
}
lte.append(packet)
return f"OK", 200
except Exception or JsonError as exc:
print(str(exc))
return "some problem"+str(exc), 201
It seems that you have to configure your logging module. You can replace the Python code print(str(exc)) with app.logger.error(str(exc)) to see if it produces some output. You can click here to find some useful code.
By the way, you can take a look at the content received by your Android client because it should receive the response "some problem"+str(exc).
I do not know much about Android code, but it seems that you are dealing with a wrong JSON string. The right format is as below:
{
"foo":"bar",
"good":"bad"
}
In your Android code, you might have to replace
"\"date\":"+"\""+send_.getString("Date")+","
to
"\"date\":"+"\""+send_.getString("Date")+"\","
The above rule should be applied to all lines in the JSON string. Be careful about the symbol "", and you have to make sure that the data during POST is a valid JSON string. Also, I suggest you use another way like utilizing some libraries to build JSON strings to avoid typos.

JAX-WS Authentication SoapUI vs. Client application

I need to create an SOAP client with JAX-WS on JBoss.
The Problem is I cannot get past the authentication.
I have a test implemented in SoapUI which works when I set the request properties username and password
With the following code
URL kbaURL = new URL("http://...");
IkfzService ikfzService = new IkfzService(kbaURL);
IkfzPortType ikfzPortType = ikfzService.getIkfzSOAP();
Map<String, Object> requestContext = ((BindingProvider)ikfzPortType).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "...");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "...");
Where URL, username und password are the same like in SOAPUI I am getting
javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException:
Failed to create service.
...
Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR:
Problem parsing 'http://..'.: java.io.IOException: Server returned HTTP response code:
401 for URL: http://..
What am I missing?
This should be a basic example of what you're trying to accomplish - let me know if you need more help or clarification
//the WSDL/webservice endpoint
private static final String WSDL_URL = "http://localhost:8080/MyWebService/MyWebService?wsdl";
URL url = new URL(WSDL_URL);
QName qname = new QName("http://ws.mycompany.com/", MyWebServiceImpl");
Service theWSService = Service.create(url, qname);
//returns the interface for MyWebServiceImpl
TheWSServiceIF port = theWSService.getPort(TheWSServiceIF.class);
//Setup Security
Map<String, Object> requestContext = ((BindingProvider)port).getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
Map<String, List<String>> requestHeaders = new HashMap<String, List<String>>();
requestHeaders.put("Username", Collections.singletonList("myUserName"));
requestHeaders.put("Password", Collections.singletonList("myPasword"));
requestContext.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
/**********************************************************************/
//actually call the web service method, print results
System.out.println(port.getMyWebServiceData());

How to use OWIN in Azure Functions?

We have a an API built using WebAPI and OWIN. Now this means that a lot of the authentication code uses OWIN classes, most of all the OwinContext, but when converting to running in Azure Functions, you're basically reduced to being a console app receiving a HttpRequestMessage.
In order to not have to reimplement our entire authorization/authentication scheme, is there any way to use OWIN in Azure Functions? Maybe by manually creating an OwinContext or something?
I'm sorry if this question is too broad, but I can't seem to fit my head around this.
Maybe by manually creating an OwinContext or something?
Yes, we can manually create it according the request message. Based on the protocol of OWIN, we need to add the required keys to Environment dictionary. Sample code below is for your reference.
Dictionary<string, object> environment = new Dictionary<string, object>();
MemoryStream requestBody = new MemoryStream();
byte[] json = Encoding.UTF8.GetBytes("{ 'a' : 'value1' }");
requestBody.Write(json, 0, json.Length);
environment.Add("owin.RequestBody", requestBody);
var headers = new Dictionary<string, string[]>();
headers.Add("host",new string[] { "myhost.com" });
headers.Add("Content-Type", new string[] { "application/json" });
environment.Add("owin.RequestHeaders", headers);
environment.Add("owin.RequestMethod", "POST");
environment.Add("owin.RequestPath", "a.html");
environment.Add("owin.RequestPathBase", "/");
environment.Add("owin.RequestProtocol", "HTTP/1.1");
environment.Add("owin.RequestQueryString", "myhost.com");
environment.Add("owin.RequestScheme", "http");
OwinContext context = new OwinContext(environment);
context.Environment.Add("owin.ResponseHeaders", new Dictionary<string, string[]>());
context.Environment.Add("owin.ResponseBody", new MemoryStream());

ServiceStack - Switch off Snapshot

I've followed instructions on how creating a ServiceStack here at:
https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice
I'm sure I have followed it to the letter, but as soon as I run the web application. I get a 'Snapshot' view of my response. I understand this happens when I don't have a default view/webpage. I set up the project as a ASP.net website, not a ASP.net MVC website. Could that be the problem?
I also wrote a test console application with the following C# code. It got the response as a HTML webpage rather than as a plain string e.g. "Hello, John".
static void sendHello()
{
string contents = "john";
string url = "http://localhost:51450/hello/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = contents.Length;
request.ContentType = "application/x-www-form-urlencoded";
// SEND TO WEBSERVICE
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(contents);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}
How can I switch off the 'snapshot' view? What am I doing wrong?
The browser is requesting html so ServiceStack is returning the html snapshot.
There are a couple of ways to stop the snapshot view:
First is to use the ServiceClient classes provided by servicestack. These also have the advantage of doing automatic routing and strongly typing the response DTOs.
Next way would be to set the Accept header of the request to something like application/json or application/xml which would serialize the response into json or xml respectively. This is what the ServiceClients do internally
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
...
Another method would be to add a query string parameter called format and set it to json or xml
string url = "http://localhost:51450/hello/?format=json";
Putting the specific format requesting is the practical way to do this
string url = "http://localhost:51450/hello/?format=json";
I suggest simply deleting this feature.
public override void Configure(Container container)
{
//...
this.Plugins.RemoveAll(p => p is ServiceStack.Formats.HtmlFormat);
//...
}
Now all requests with the Content-Type=text/html will be ignored.

kSoap API for J2ME

i am using ksoap/ksoap2 api for calling a php webservice from j2me.
For ksoap:
SoapObject client = new SoapObject(NAMESPACE, "ns2221:save_record");
client.addProperty("cc", "1234560789");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
XmlWriter xw = new XmlWriter(new OutputStreamWriter(bos));
SoapEnvelope envelope = new SoapEnvelope(new ClassMap(Soap.VER11));
envelope.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
envelope.setBody(client);
envelope.write(xw);
xw.flush();
bos.write('\r');
bos.write('\n');
byte[] requestData = bos.toByteArray();
String requestSOAPmesg = new String(requestData);
System.out.println("request Soap Message: " + requestSOAPmesg);
HttpTransport ht = new HttpTransport();
ht.setUrl(url);
ht.setSoapAction(NAMESPACE);
SoapObject o = (SoapObject) ht.call(client);
have used..
and in ksoap2
SoapObject client = new SoapObject("http://192.168.0.205:82/imageuploader/save_record.php#save_record", "ns8862:save_record");
client.addProperty("cc", "1234560789");
//Create Envelope for
Object so=soapMsg;
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=false;
envelope.bodyOut=client;
System.out.println("Before Envelope");
HttpTransport ht = new HttpTransport(url);
ht.call("http://192.168.0.205:82/imageuploader/save_record.php#save_record", envelope);
SoapObject o=(SoapObject) envelope.getResponse();
have used..
it returns me
fault String:
faultstring: 'Operation 'ns8862:save_record' is not defined in the WSDL for this service' faultactor: '' detail: org.kxml2.kdom.Node#ea0ef881
in the web service the first tag ns8862:save_record changes every time a request is passed for the 4 numbers.
Any Solution?
Check the web service for capital letters. The error states that "save_record" is undefined. Maybe it's "Save_Record", or "saveRecord". Make sure you are adhering to the template.

Resources