java application to read information from ARIN RESTful Web Services - java

I am trying to create a java application to read the information from ARIN using an IP Address. I see ARIN is using RESTful Web Services to get the IP information but I am not sure what I need to do to start. Some people are talking about RESTLET, other people about JAX-RS,etc. Can you please help me to take me in the right direction? Thanks!

Restlet also has a client API to interact with a remote RESTful application. See the classes Client, ClientResource for more details. For this, you need to have following jar files from Restlet distribution:
org.restlet: main Restlet jar
org.restlet.ext.xml: Restlet support of XML
org.restlet.ext.json: Restlet support of JSON. In this case, the JSON jar present in libraries folder is also required.
If I use the documentation located at this address https://www.arin.net/resources/whoisrws/whois_api.html#whoisrws. Here is a simple Restlet code you can use:
ClientResource cr = new ClientResource("http://whois.arin.net/rest/poc/KOSTE-ARIN");
Representation repr = cr.get();
// Display the XML content
System.out.println(repr.getText());
or
ClientResource cr = new ClientResource("http://whois.arin.net/rest/poc/KOSTE-ARIN.txt");
Representation repr = cr.get();
// Display the text content
System.out.println(repr.getText());
Restlet also provides some support at XML level. So you can have access to hints contained in the XML in a simple way, as described below:
ClientResource cr = new ClientResource("http://whois.arin.net/rest/poc/KOSTE-ARIN");
Representation repr = cr.get();
DomRepresentation dRepr = new DomRepresentation(repr);
Node firstNameNode = dRepr.getNode("//firstName");
Node lastNameNode = dRepr.getNode("//lastName");
System.out.println(firstNameNode.getTextContent()+" "+lastNameNode.getTextContent());
Note that you can finally handle content negotiation (conneg) since it seems supported by your REST service:
ClientResource cr = new ClientResource("http://whois.arin.net/rest/poc/KOSTE-ARIN");
Representation repr = cr.get(MediaType.APPLICATION_JSON);
In this case, your representation object contains JSON formatted data. In the same way than the DomRepresentation, there is a JsonRepresentation to inspect this representation content.
Hope it helps you.
Thierry

The problem is that you don't seem to understand very well what REST is (sorry if I'm mistaken!). Restlet and JAX-RS are both server-side related.
You probably need something like jersey-client. This is a library which helps to interact with RESTful webservices.
You could also usa plain Java libraries to make HTTP calls to the webservice. REST is tightly bound to its implementation protocol. This means that if the webservice is implemented in HTTP (most likely is) you don't need anything fancy to interact with it. Just HTTP.
I strongly encourage you to learn more about REST and HTTP itself.

Related

Sending Java/Kotlin objects to RSocket route

I've set up #MessageMapping endpoint using Spring's RSocket support and tested it with RSocketRequester. This flow is working perfectly since Spring handles bunch of low-level stuff for us.
Now, I'd like to have some sort of UI to show whatever data I'm working with and do any UI updates on that data through mentioned #MessageMapping endpoint. The problem is that I have no idea how to send full Java/Kotlin object (as JSON) to my endpoint using either rsocket-java or rsocket-kotlin libraries. Since I have to send both data and metadata and metadata is encoded as ByteBuf I had to encode JSON to ByteBuf, but it comes to endpoint all messed up and it cannot be deserialized.
I've also tried sending raw string value and it also comes to endpoint all messed up (bunch of non-UTF chars). I've tried both APPLICATION_JSON and TEXT_PLAIN for data mime type, but it didn't work for either.
Also, I guess whatever I'm doing wrong is not strictly related to Java/Kotlin libraries, but can be applied to any other existing RSocket library (Go, Rust, JS, etc.)
If you are using an rsocket-kotlin client (not building on spring-boot) then you can copy the code from https://github.com/rsocket/rsocket-cli/blob/master/src/main/kotlin/io/rsocket/cli/Main.kt
It builds metadata for the route with
this.route != null -> {
CompositeMetadata(RoutingMetadata(route!!)).toPacket().readBytes()
}
I guess I've figured it out.
I've scratched that binary encoded metadata and borrowed what I found on the internet for RSocket in JavaScript and it worked :)
So, the solution is to use routing metadata mime type (I was using composite since example I found was using it) and the payload then can be created like this:
val json = "{}"
val route = "myawesomeroute"
DefaultPayload.create(<json>, "${route.length.toChar()}$route")

use existing http client for SOAP call

I've got a working Dropwizard project, which has several ways of getting data it needs. One of those ways is the JAX-RS client that Dropwizard provides, the JerseyClient. This client is configured so that it suits my needs (uses the proper proxy, timeouts etc...)
Now my project has a new requirement for which I need to do a SOAP call. I've got that functionally working using the following code:
// not the actual structure, edited to make a minimal example
// SERVICE_QNAME and PORT_QNAME are hardcoded strings, config.url comes
// from the configuration
import javax.xml.ws.*;
import javax.xml.ws.soap.*;
import javax.xml.namespace.QName;
Service service = Service.create(SERVICE_QNAME);
service.addPort(PORT_QNAME, SOAPBinding.SOAP11HTTP_BINDING, config.url);
Dispatch dispatch = service.createDispatch(PORT_QNAME, SOAPMessage.class, Service.Mode.MESSAGE);
dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, config.url);
Message message = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL).createMessage();
// do stuff to fill the message
response = dispatch.invoke(message);
This is all out-of-the-box behaviour, anything happening here is provided either by java (8) or Dropwizard.
This code however uses it's own http connectors, bypassing anything I've set up in my JAX-RS client. I would like to re-use the JerseyClient's http capabilities in the JAX-WS client in a non-copy-paste kinda way.
Is there a way I can set up the Dispatch so that it will use the existing http connectors? Or some other SOAP client to achieve the same?
Thank you #zloster for the research and suggestions. I decided to take another route however.
I found the SAAJ standard and am using that now. I created a subclass for javax.xml.soap.SOAPConnection and based that on com.sun.xml.internal.messaging.saaj.client.p2p.HttpSOAPConnection. That part wasn't all that hard and leaves me with a relatively small class.
Now in my code I replaced the code above with something along these lines:
SOAPConnection soapConnection = new JerseySOAPConnection(httpClient, soapProtocol);
Message message = MessageFactory.newInstance(soapProtocol).createMessage();
// do stuff to fill the message
response = soapConnection.call(message, config.url);
Due to my implementation not all that portable, but I don't really need it to be. Again, thanks for those who helped me get to this!

REST call in Java

I have a few questions about a specific REST call I'm making in JAVA. I'm quite the novice, so I've cobbled this together from several sources. The call itself looks like this:
String src = AaRestCall.subTrackingNum(trackingNum);
The Rest call class looks like this:
public class AaRestCall {
public static String subTrackingNum (Sting trackingNum) throws IOException {
URL url = new URL("https://.../rest/" + trackingNum);
String query = "{'TRACKINGNUM': trackingNum}";
//make connection
URLConnection urlc = url.openConnection();
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc
.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line=br.readLine())!=null) {
sb.append(line);
}
br.close();
return sb.toString();
}
}
Now, I have a few questions on top of the what is wrong with this in general.
1) If this rest call is returning a JSON object, is that going to get screwed up by going to a String?
2) What's the best way to parse out the JSON that is returning?
3) I'm not really certain how to format the query field. I assume that's supposed to be documented in the REST API?
Thanks in advance.
REST is a pattern applied on top of HTTP. From your questions, it seems to me that you first need to understand how HTTP (and chatty socket protocols in general) works and what the Java API offers for deal with it.
You can use whatever Json library out there to parse the HTTP response body (provided it's a 200 OK, that you need to check for, and also watch out for HTTP redirects!), but it's not how things are usually built.
If the service exposes a real RESTful interface (opposed to a simpler HTTP+JSON) you'll need to use four HTTP verbs, and URLConnection doesn't let you do so. Plus, you'll likely want to add headers for authentication, or maybe cookies (which in fact are just HTTP headers, but are still worth to be considered separately). So my suggestion is building the client-side part of the service with the HttpClient from Apache commons, or maybe some JAX-RS library with client support (for example Apache CXF). In that way you'll have full control of the communication while also getting nicer abstractions to work with, instead of consuming the InputStream provided by your URLConnection and manually serializing/deserializing parameters/responses.
Regarding the bit about how to format the query field, again you first need to grasp the basics of HTTP. Anyway, the definite answer depends on the remote service implementation, but you'll face four options:
The query string in the service URL
A form-encoded body of your HTTP request
A multipart body of your HTTP request (similar to the former, but the different MIME type is enough to give some headache) - this is often used in HTTP+JSON services that also have a website, and the same URL can be used for uploading a form that contains a file input
A service-defined (for example application/json, or application/xml) encoding for your HTTP body (again, it's really the same as the previous two points, but the different MIME encoding means that you'll have to use a different API)
Oh my. There are a couple of areas where you can improve on this code. I'm not even going to point out the errors since I'd like you to replace the HTTP calls with a HTTP client library. I'm also unaware of the spec required by your API so getting you to use the POST or GET methods properly at this level of abstraction will take more work.
1) If this rest call is returning a JSON object, is that going to get
screwed up by going to a String?
No, but marshalling that json into an obect is your job. A library like google gson can help.
2) What's the best way to parse out the JSON that is returning?
I like to use gson like I mentioned above, but you can use another marshal/unmarhal library.
3) I'm not really certain how to format the query field. I assume
that's supposed to be documented in the REST API?
Yes. Take a look at the documentation and come up with java objects that mirror the json structure. You can then parse them with the following code.
gson.fromJson(json, MyStructure.class);
Http client
Please take a look at writing your HTTP client using a library like apache HTTP client which will make your job much easier.
Testing
Since you seem to be new to this, I'd also suggest you take a look at a tool like Postman which can help you test your API calls if you suspect that the code you've written is faulty.
I think that you should use a REST client library instead of writing your own, unless it is for educational purposes - then by all means go nuts!
The REST service will respond to your call with a HTTP response, the payload may and may not be formatted as a JSON string. If it is, I suggest that you use a JSON parsing library to convert that String into a Java representation.
And yes, you will have to resort to the particular REST API:s documentation for details.
P.S. The java URL class is broken, use URI instead.

Java: handling webcal protocol

I'm trying to download - or even just open a stream - to a calendar located at webcal://www.somewhere.com/foo?etc=bar.
The Java URL class is throwing a "unknown protocol: webcal" exception when I do:
URL url = new URL("webcal://...");
How can I tell the URL class that it should just use HTTP as trasport protocol even if the web resource is located somewhere behind a webcal:// protocol?
Or, in any case, how can I get my calendar downloaded?
Please, bear in mind that the web server I'm calling does not serve the calendar if I try to replace the "webcal://" with "http://".
As far as I understand, Apple's use of "webcal" really is just a synonym for "http"; so it's supposed to work.
The "webcal://" is an unofficial URI scheme, see Wikipedia article on it.
As such it might stand for one or another back end implementation - e.g. the web server you are calling might be using any of the mentioned protocol implementations, such as WebDAV, CalDAV or OpenDAV
However if all you want is to read the contents of the file, then any HTTP client should do the trick, because the above mentioned protocols are based on HTTP.
Here is an example on how to read a remote iCal using URL's own mechanism for opening HttpURLConnection :
URL calendarURL = new URL("http://www.facebook.com/ical/b.php?uid=myUID&key=myKEY");
URLConnection connection = calendarURL.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (reader.ready()) {
System.out.println(reader.readLine());
}
As you can see I have changed the original URL from
webcal://www.facebook.com/ical/b.php?uid=MYUID&key=MYKEY
to
http://www.facebook.com/ical/b.php?uid=MYUID&key=MYKEY
, because we use a java.net.URL and by default Java does not recognize this protocol. If indeed the web server you want to contact only serves the content over webcal:// then you might need to use the appropriate client (based on the exact protocol implementation the server uses). For example there are a multitude of frameworks that provide WebDAV client capabilities, such as JackRabbit, Sardine, etc.
If you provide more information on the type of server we can dig further.

Using a JSON web service from a Java client application

I am developing a client-side Java application that has a bit of functionality that requires getting data from some web services that transmit in JSON (some RESTful, some not). No JavaScript, no web browser, just a plain JAR file that will run locally with Swing for the GUI.
This is not a new or unique problem; surely there must be some open source libraries out there that will handle the JSON data transmission over HTTP. I've already found some that will parse JSON, but I'm having trouble finding any that will handle the HTTP communication to consume the JSON web service.
So far I've found Apache Axis2 apparently which might have at least part of the solution, but I don't see enough documentation for it to know if it will do what I need, or how to use it. Maybe part of the problem is that I don't have experience with web services so I'm not able to know a solution when I see it. I hope some of you can point me in the right direction. Examples would be helpful.
Apache HttpClient 4.0
is the best in the business and is moderately easy to learn.
If you want easier you could use HtmlUnit which imitates the behaviour of browsers so you could easily get the content (and parse it into Html, javascript and css, you could also execute javascript code on content so you could probably parse JSON files to using JSON.parse or any other equivalent functions) of any page on the web.
so for HtmlUnit here is a sample code:
WebClient wc = new WebClient(BrowserVersion.FIREFOX_3_6);
HtmlPage page = wc.getPage("http://urlhere");
page.executeJavaScript("JS code here");
but it maybe rather heavy for your requirements so a highly recommend the use of HttpClient library.
I'm sure you could find many JSON libraries for java but here is one for you json-lib
I did it using a simple Java JSON libary. Use the Google library..
URL url = new URL("http://www.siteconsortium.com/services/hello.php");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
JSONParser parser=new JSONParser();
Object object = parser.parse(in);
JSONArray array = (JSONArray) object;
JSONObject object2 = (JSONObject)array.get(0);
System.out.println(object2.get("hello"));
If the webservice uses OAuth and an access token you can't use the above example though.
Its great to see that your web services are RESTful. RESTful web services are pretty easy to develop and to consume.Well... you do not need to take any extra care to tranmit JSON data over the network... Data whether is in JSON on in XML format are embedded into the HTTP header..Following code snippet will help you understand the idea :
httpConnection = new HTTPConnectionManager(request);
HttpURLConnection httpURLConnection = httpConnection.connect();
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = httpURLConnection.getInputStream();
int x;
StringBuilder stringBuilder = new StringBuilder();
while ((x = in.read()) != -1) {
stringBuilder.append((char) x);
}
XMLParser xmParser = new XMLParser();
....
....
}
In this code i am receiving data in XML format from web services.After receiving the data into a StringBuilder object,i am parsing the XML. In the same way you can call your web services using this code and can receive your JSON data. you can use javaJSON APIs,available Here, to extract the data from JSON notation.
Hope code will help you...
PS: HTTPConnectionManager,XMLParser and Request(request object) classes are not any standard APIs. they are written by my own account to handle multiple web service calls. This code snippet is just to give you my idea.

Categories

Resources