I'm developping an Eclipse RCP Application that have to display in a Treeview the collections of a DataBase.
The collections of the DataBase are provided by a REST API.
So, what i have to do is to call the REST API by given the URL and the KEY and display result (The collections) in the Treeview.
What i know about REST API is that it's used (most of the time) in web applications, but it's not the case for me.
Does anybody know how to call a REST API from an Eclipse RCP Application ?
Does someone have an experience with RCP and REST API ?
Thanks in advance.
Ismail
You should be able to use whatever java rest client you want. I personnaly preferred using jersey because sometimes using Spring Framework inside Eclipse can be painful.
It worked for me adding all these librairies :
lib/jsr311-api-1.1.1.jar,
lib/jersey-client-1.19.jar,
lib/jersey-core-1.19.jar,
lib/jersey-json-1.19.jar,
lib/jackson-core-asl-1.9.2.jar,
lib/jackson-jaxrs-1.9.2.jar,
lib/jackson-mapper-asl-1.9.2.jar,
lib/jaxb-api-2.2.2.jar,
lib/jaxb-impl-2.2.3-1.jar,
lib/jackson-xc-1.9.2.jar
And a simple call is as follow :
try {
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client.resource("http://localhost:8080/getMyObject");
ClientResponse response = webResource.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
MyObject output = response.getEntity(MyObject.class);
} catch (Exception e) {
//Handling errors
}
JSONConfiguration.FEATURE_POJO_MAPPING is for the auto mapping to json using jersey-json and jackson-*.jar
To call the RestAPi, i've used the SpringFramework using this :
org.springframework.web.client.RestTemplate and its methods.
Related
The vertx implementation of calling / invoking / consuming the REST APIs through requestAbs method
of io.vertx.core.http.HttpClient class from vertx-core-3.2.0.jar results in HTTP Error :: 302 and Response Data as HTML Erro Response .
Not sure how the requestAbs method behaves as there's no exception thrown and it does not write any logs as well.
Also source code attached for this method with vertx jars. Suspect, if the method implementation has a bug?
The same REST API calls are success with Browser / POSTMAN.
The traditional approach with Apache HTTPClient for REST Calls are success, then I doubt why not with vertx framework.
Any solution / modification in code snippet below is much appreciated.
Thanks
Code
Your code is a bit confusing (it looks like variables names are not always the same).
Anyway, you will manage to do what you want with that code:
final HttpClient httpClient = vertx.createHttpClient();
final String url = "http://services.groupkt.com/country/get/iso2code/IN";
httpClient.getAbs(url, response -> {
if (response.statusCode() != 200) {
System.err.println("fail");
} else {
response.bodyHandler(b -> System.out.println(b.toString()));
}
}).end();
Hope this will help.
I'm consuming a REST api using the RestBuilder plugin. I get a response where the body is compressed:
Content-Encoding=[gzip]
Does groovy/Grails provide any easy access / native methods for decoding gzip compression? The only thing I found is the native Java zip api (ex. GZIPInputStream). Does someone have a better idea?
basically, you have 2 options here:
GZIPInputStream
configure GZIP-decompression in tomcat, see here
Spring and HttpComponents will handle the decoding automatically:
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder.create().build());
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
ResponseEntity<String> response = restTemplate.exchange(
"some/url/", HttpMethod.GET, new HttpEntity<Object>(requestHeaders),
String.class);
I am new to couchdb and I want to learn about how to connect the couchdb in our gwt server side program. till now, I tried to work on its gui to create database add documents and add fields to it.but i am not able to use it in program. what exactly the way to do it..
I tried some code but didn't got it.
In your GWT you should have something like this in your server. Besides it you should have your DAO for your Entities (erktorp takes place here) and your mechanism for connecting GWT's client with the server (for example RequestFactory).
//Object of your own related with couch db management
CouchDbAccess couchDbAccess = null;
#Inject
public CouchDbManagement(String ddbbUrl, String ddbbName) throws IOException {
HttpClient httpClient;
Builder b;
try {
b = new StdHttpClient.Builder().url(ddbbUrl);
} catch (Exception e) {
e.printStackTrace();
ddbbUrl = "http://admin:sa#localhost:5984";
b = new StdHttpClient.Builder();
}
b.socketTimeout(60000);
String user = getUserFrom(ddbbUrl);
String pass = getPassFrom(ddbbUrl);
b.username(user).password(pass);
httpClient = b.build();
CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
if (initialize && dbInstance.getAllDatabases().contains(ddbbName)) {
dbInstance.deleteDatabase(ddbbName);
dbInstance = new StdCouchDbInstance(httpClient);
}
//If you want Lucene, here is the place
db.createDatabaseIfNotExists();
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
new IndexUploader().updateSearchFunctionIfNecessary(db, ...);
URI dbURI = URI.prototype(DbPath.fromString(ddbbName).getPath());
RestTemplate restTemplate = new RestTemplate(dbInstance.getConnection());
couchDbAccess = new CouchDbAccess(db, dbURI, restTemplate);
}
Couchdb has a restful interface to it's api. Everything is available via url's like
http://localhost:5984/db_name/doc_name
In fact the entire http api is documented in the wiki. Now I am not familiar with gwt but every framework has http libraries and you can use those libraries to make calls to couchdb http endpoints.
A quick google search gave me this resource which may guide you on how to create http requests through gwt.
I am using Jena API to get RDF data from Allegrograph Server. I have written a REST webservice using Jersey jar to get this data.
My java code for the webservice is as shown below:
#GET
#Path("/JENA")
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public String getData() throws RepositoryException {
AGGraphMaker maker = new AGGraphMaker(conn);
AGGraph graph = maker.getGraph();
AGModel model = new AGModel(graph);
AGQuery agQuery = AGQueryFactory.create(query);
QueryExecution qe = AGQueryExecutionFactory.create(agQuery, model);
String result = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
ResultSet rs = qe.execSelect();
While(rs.hasNext()){
byteArrayOutputStream = new ByteArrayOutputStream();
if("JSON".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsJSON(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
System.out.println("Result is "+result);
} else if("XML".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsXML(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}else if("CSV".equalsIgnoreCase(outputFormat)){
ResultSetFormatter.outputAsCSV(byteArrayOutputStream, rs);
result = byteArrayOutputStream.toString();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
I get no results for the SPARQL query when I deploy this web service on Tomcat server and test it using REST client app on Chrome and firefox.
But the same code(absolutely no difference in webservice code and this main method code) if I write in a plain java class and run its main method, i am getting 36 results. I am not sure what the issue is.
Please help me in this regard.
You need to separate the concerns:
Move the service logic - the bit that actually queries Allegro graph - to a separate class so that it's properly encapsulated. The API for the class should reflect its responsibilities in your application, not the way that it happens to be working at the moment.
Write JUnit tests for the service class. This is important - it gives you confidence that your service is performing its job correctly, and keeps on doing so as you develop your application.
Write your Jersey method to invoke any service object that conforms to the API of your service class.
Write one or more HTTPUnit (or similar) tests to invoke your REST API. Ideally, you'll use a mock or test double instead of the actual service. What you want to test is whether the HTTP request reaches the right method, and that method delegates to the service object with the right arguments. You're then testing (and debugging!) a smaller number of concerns.
It's much better to work with small units of functionality with a clear idea of what their responsibilities are. And you should definitely learn to work with tests - it's a big win in the medium term, even if it means a bit more learning up front!
I have a single GWT web-application integrated with Spring MVC. I have a working Controller which works perfectly and is unit tested to accept POSTed JSON data and returns JSON data.
From within the same application, to avoid any SOP cross-site domain issues, I am making a call with a RequestBuilder to POST the same json data, and I expect JSON data back.
I created a basic java class that should make a call, but I have a few issues. This running web-app is running in hosted mode in Jetty in Eclipse. I have done a ton of research on how GWT should make a call to an existing web-service with a simple HTP request.
The first issue from my unit test is that:
String baseUrl = GWT.getModuleBaseURL();
is not working and I get:
java.lang.UnsatisfiedLinkError: com.google.gwt.core.client.impl.Impl.getModuleBaseURL()Ljava/lang/String;
I think I know what the correct URL should be, so when I hard-code the url correctly, and execute this code:
String url = getRootUrl() + "rest/pendingInvoices/searchAndCount";
System.out.println("PendingInvoiceDataSource: getData: url=" + url);
// Send request to server and catch any errors.
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Accept", "application/json");
builder.setHeader("Content-type", "application/json");
// builder.setRequestData(requestData);
try
{
System.out.println("PendingInvoiceDataSource: SEND REQUEST: getData: requestData=" + requestData);
Request request = builder.sendRequest(requestData, new RequestCallback()
{
public void onError(Request request, Throwable exception)
{
System.out.println("Couldn't retrieve JSON");
}
#Override
public void onResponseReceived(Request request, Response response)
{
if (200 == response.getStatusCode())
{
// updateTable(JsonUtils.safeEval(response.getText()));
System.out.println("data=" + response.getText());
}
else
{
System.out.println("Couldn't retrieve JSON (" + response.getStatusText() + ")");
}
}
});
}
catch (RequestException e)
{
System.out.println("Couldn't retrieve JSON");
}
I get this error on he sendRequest:
java.lang.UnsatisfiedLinkError: com.google.gwt.xhr.client.XMLHttpRequest.create()Lcom/google/gwt/xhr/client/XMLHttpRequest;
at com.google.gwt.xhr.client.XMLHttpRequest.create(Native Method)
at com.google.gwt.http.client.RequestBuilder.doSend(RequestBuilder.java:383)
at com.google.gwt.http.client.RequestBuilder.sendRequest(RequestBuilder.java:261)
I think this might be a quick fix, or maybe something small I have forgotten, so I'll try some more testing and see what I can find.
Everything client in GWT is only meant to run on the client-side: compiled to JS or in DevMode.
Only shared, server and vm classes can be used on the server-side.
If you want to get your server URL, use the appropriate methods from the HttpServletRequest (or whatever it is in Spring MVC as it seems from how you tagged the question that's what you're using).
If you want to make HTTP requests from your server, use an HttpURLConnection, or OkHttp, Apache Http Components or similar libraries, or even Spring's own HTTP client API.
Actually, it was only the Unit Test that was having a problem. Once I actually tried to run the deployed code, it all worked. I'll still try h GWTTestCase as suggested in order to get the unit test working.
But everything worked correctly when I ran the deployed code.
I also changed: String baseUrl = GWT.getModuleBaseURL();
which gave me:
http://localhost:8888/MyProject
To: String baseUrl = GWT.getHostPageBaseURL();
which gave me:
http://localhost:8888/
and that all worked.