how to handle db connectivity of couchdb with gwt? - gwt

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.

Related

Alternative to REST when passing objects between servers

I have a spring-mvc project as a frontend project. My datasources are accessed by a second javaee project. This backend grands access to all data my frontend requires, by providing REST services. The REST-Service provides objects, by returning XML. This XML will then get marshaled by my frontend.
So when my frontend project requires current data, I create an HttpUrlConnection, then I call the REST-Service of my backend.
E.g. I want to get a collection of all movie objects:
URL url = new URL(URLSAFE.REST_ALL_MOVIES);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/xml");
connection.getResponseCode();
InputStream is = connection.getInputStream();
Source sauce = new StreamSource(is);
JAXBContext jaxbContext = JAXBContext.newInstance(Movies.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<Movies> e = unmarshaller.unmarshal(sauce, Movies.class);
Movies m = e.getValue();
this.MOVIELIST = m;
connection.disconnect();
After I added some remote ejb lookups for logging services, I came up with the idea to use rmi for passing objects. However I learned I cant cast the object to my frontend and that there is a big difference between a local object and a object you access by rmi.
But what would be a good attempt for passing objects between servers? I need to pass objects to the frontend because I got to use them with JSP.
I would suggest to take a look at this Spring.io guide. Usage of RestTemplate can remove a lot of boilerplate you have in example, and map REST resources onto POJOs. XML shouldn't be any barrier, because Spring should significantly help you abstract it.

Eclipse 4 Application RCP and a REST API

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.

Jena API with REST webservice using Jersey

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!

RPCManager RPCRequest how to capture the response in gwt

hi i have requirement to capture the data for validations. i am able to fetch the data using RPCRequest and RPCManager by using setActionUrl to the controller class.from there creating the service class and dao classes .i am able to fetch the data into controller class.but i am unable get the data back into my grid.i want the data to be fetched into a variable.i am not using asynchronus service.i used async method in grid i am able to fetch into onSuccess() method.but without using how i can fetch.the data into grid.
with regards
subodh
Here example in our ServiceImpl class to retrive datas from DB
public final String getDatas(final HashMap<String, String> param) {
List<ShippingBean> result = null;
JSONObject obj = new JSONObject();
try {
// retrieve data from DB
data = dao.selectAll();
}
catch (BusinessException e) {
throw new InvocationException("BusinessException occurs ...", e);
}
obj = JSONObject.fromObject(result);
return obj.toString();
}
We use net.sf.json to serialize as DOM and return this to presenter call as AsyncCallBack method. And then , retrieve data as like that..
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("Error!");
}
public void onSuccess(final String result) {
HTML html = new HTML(result.replace(" ", "-"));
JSONValue value = JSONParser.parseLenient(html.getText());
JSONWrapper json = new JSONWrapper(value);
System.out.println(json.get(0).get("variableName").stringValue());
}
};
I have done something similar within a project with retrieve data and posting it to GWT from database. My database setup was Microsoft SQL 2012 and Hibernate framework to retrieve it. However I created a custom try/catch block and if/else bocks for validation on client side.
I used this tutorial from Hibernate to GWT to set up the transactions between the web application and the database for both saving and retrieving. Their source code provides the web page modules for setting up the displaying which I mimicked to fit to my needs since I was not storing "records" or "users".
GWT does have a validation setup but I spent a 10 hours trying to figure out the client side validation and gave up for something much simpler such as try/catch on the data being submitted since I had no concern for the format of the numbers.
Google "GWT Validation" and you should have some documentation about it but their isn't that much to choose from since everything seems to be a copy of Google's documentation.
Link - Hibernate to GWT
Hope this helps or points you in the right direction towards your answer.

SOAPUI : Need Sample REST APIs to test using SOAPUI Tool

Hi Can anyone let me know where I can find sample RESTFul APIs so that I can have hands on experience working on them using GET/POST/DELETE methods.
Thanks.
If you have an idea about Java, Servlet, Wildfly / Tomcat server, Mysql then you can create a basic program for Get / Post Method and deploy on the local server.
You will learn to create basic API also. The best way you install eclipse and integrate server. With Eclipse, you can easily create Servlet as it provides template and web.xml generate automatically.
Create a basic object Class. Call it in servelet fill some data.
Convert it to JSON by using GSON
#WebServlet(asyncSupported = true, urlPatterns = { "/School_getEmployee" })
public class School_Employee_servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(Object);
PrintWriter out = response.getWriter();
out.println(json);
}
Now you can use this servlet as API for testing.
You can use JSON-SERVER, I'm using these to make GET/PUT/POST/DELETE