developing a webservice using java and mysql - java

I am not familiar with websrvices and mysql ..i followed this http://www.vogella.com/articles/REST/article.html tutorial and developed a RESTful web service in Java with the JAX-RS reference implementation Jersey.
I want to create an websrevice using eclipse which select the data from mysql database and display the result in xml format.
I got lots of sample developing webservices with PHP and mysql but i want to develop in java.
Please suggest me some good tutorial/links on this or idea which may help me. i want to use that webservice in my android application.
In the above example ,i am not getting where to put the connection string to establish the connection between MySQL database and java files.
Here is the TodoResource.java :
package de.vogella.jersey.jaxb;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import de.vogella.jersey.jaxb.model.Todo;
#Path("/todo")
public class TodoResource {
// This method is called if XMLis request
#GET
#Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
//#Produces( { MediaType.TEXT_XML })
public Todo getXML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
todo.setMy_id(1);
return todo;
}
// This can be used to test the integration with the browser
#GET
#Produces( { MediaType.TEXT_XML })
public Todo getHTML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
}

I would start here : http://wiki.restlet.org/docs_2.1/13-restlet/21-restlet.html
You can create a java class/method that encapsulates the Business logic, for example a method like getData(DataFormat xml/html, whatData) which connects to the mysql database and retrieves records and then transforms it into required format, call this method within getXML() and getHTML()

Spring MVC makes REST based development very easy. Refer to this blog

The example you linked to does not actually make use of a database but uses in-memory Todo's to provide the data. In section 8 the author states
Create the following data model and a Singleton which serves as the
data provider for the model. We use the implementation based on an
enumeration.
The data model is the Todo class.
The data provider is the TodoDao enum. The purpose of TodoDao, is essentially to store Todo's in memory. In other words, it performs the function that would otherwise be done by a database.
What therefore needs to be done, is to:
Replace TodoDao with a database.
Map Todo to a table in the database.
To connect Java objects to a database, you can use an Object Relational Mapper (ORM), which can be achieved by using the Java Persistence API (JPA).
Therefore, to map Todo to a database table, it needs to be annotated with JPA annotations, thus creating a JPA Entity.
Have a look the accepted answer to REST/JSON Web Services Java EE Framework, it should shed some light on what needs to be done. Part 1 covers creating a database, while Part 2 covers creating and annotating JPA entities (Part 3 - JAXB Bindings for xml or json, Part 4 - The RESTFul Service, Part 5 - The Client).
If difficulties are still encountered, have a look at the answer I posted for Need to write a RESTful JSON service in Java, that should be suitable for someone who wants more nitty-gritty to, as a starting point, connect to a single table in a database and create a RESTful Web Service with JSON/XML representations using the following.
IDE: Eclipse IDE for Jave EE Developers (Kepler), comes with Maven built in
Database: MySQL (also makes use of MySQL Workbench)
Application Server: GlassFish 4.0
Java EE 7 (JAX-RS, JPA, JAXB, etc)
Any REST Client for testing: (eg Postman)

Related

What is the essence of "exposing" an API especially in Google Cloud Endpoint?

I am totally new to the whole Google Cloud Endpoint/Google App Engine world. If you have gone through the Hello World example that Google provides(and you probably have), you might remember that there are 2 classes that are auto-generated for you: MyBean and MyEndpoint.
These are something like this:
/**
* The object model for the data we are sending through endpoints
*/
public class MyBean {
private String myData;
public String getData() {
return myData;
}
public void setData(String data) {
myData = data;
}
}
And,
/**
* An endpoint class we are exposing
*/
#Api(
name = "myApi",
version = "v1",
namespace = #ApiNamespace(
ownerDomain = "backend.myapplication.DJ.example.com",
ownerName = "backend.myapplication.DJ.example.com",
packagePath = ""
)
)
public class MyEndpoint {
/**
* A simple endpoint method that takes a name and says Hi back
*/
#ApiMethod(name = "sayHi")
public MyBean sayHi(#Named("name") String name) {
MyBean response = new MyBean();
response.setData("Hi, " + name);
return response;
}
}
Now, I examined the code in index.html(which gets opened on deploying the backend). I found the following call in the javascript:
gapi.client.myApi.sayHi({'name': name}).execute(
Now, I can see that myApi is the name through annotation and sayHi() is the corresponding method, What I don't understand is the concept of exposing an API and annotation is aiding in that. There isn't any information about exposing APIs.
Could anyone help me understand this?
I think your question can be divided in 3 parts:
1/ What is exposing an API?
Basically, you are offering an access to your business logic through an Interface (the API), with full control on what you want to show or not. This Stack Exchange answer is a great explanation: https://softwareengineering.stackexchange.com/questions/203844/what-does-it-mean-to-expose-something
2/ What are these annotations in the auto-generated endpoints class?
If I can summarize it like that, Google endpoint is a "framework" which generates "default" APIs based on your java beans. By default you get CRUD operations in the API, but you can modify and/or enrich the endpoint to offer more complex business logic. The Endpoints classes that are generated include specific annotations that are used by the framework (in particular while generating a corresponding servlet) and define the URI you will call to interact with the methods of the APIs. See https://cloud.google.com/appengine/docs/java/endpoints/
3/ What is this gapi.client call?
gapi stands for Google API Client Library. It is the library that is offered by Google to interact with Endpoints from a web browser. See https://developers.google.com/api-client-library/javascript/
You could use other methods to call the Endpoint APIs, like jquery Ajax methods (http://api.jquery.com/jquery.ajax/), since Endpoints follow the REST architectural style. Note that you can call your endpoints from other "clients" than a web browser, e.g. an Android or iOS App. In these cases, you would not use the Google API Client Library but some other libraries.
I hope this clarifies a bit. Do not hesitate to ask for more details.

Calling standard contact Seibel Business Service from Java application

I want to call the standard "Contact" Seibel Business Service from my java program. I will appreciate if you can point me to some resources on the same.
Thanks.
There are bunch of documentation and samples online.
You need to replace the Echo service by the Contact service.
I post just an example from Oracle website below:
Aside from the business object and business component API, the primary
point of integration with the Siebel application is by using business
services. There are several ways to invoke a business service. The
simplest way is using the Siebel Java Data Bean directly, as shown in
the following example.
Alternatively, Siebel Tools provides a Code
Generator which creates, for any business service, Java classes that
invoke the business service. The generated code may invoke the
business service either using the Siebel Java Data Bean or using the
Siebel Resource Adapter. The creation and use of generated code is
described in the next section. The Siebel Resource Adapter is part of
the Java EE Connector Architecture, which is described in About the
Siebel Resource Adapter. The following is an example of invoking a
business service directly using the Siebel Java Data Bean.
import com.siebel.data.SiebelException;
import com.siebel.data.SiebelPropertySet;
import com.siebel.data.SiebelService;
public class BasicDataBeanTest {
public static void main(String[] args) throws SiebelException {
SiebelDataBean dataBean = new SiebelDataBean();
dataBean.login("siebel://mymachine:2321/siebel/SCCObjMgr_enu", "USER", "PWD", "enu");
SiebelService businessService = dataBean.getService("Workflow Utilities");
SiebelPropertySet input = new SiebelPropertySet();
SiebelPropertySet output = new SiebelPropertySet();
input.setValue("Please echo this");
businessService.invokeMethod("Echo", input, output);
System.out.println("Output: " + output.toString());
}
}

Making an address book application using JAVA

I am a Java beginner and am going to make a small address book client program using java swing.
And my goal is implementing 3-tier architecture. (No sql queries are in client program)
What would be the best approach for this?
I thought (Java EE)--(XML or JSON)--(MySQL) would be the one, but isn't it too hard for beginner? :)
What else could be?
Thank you for reading my question!
Depends on what you mean by Java EE (J2EE is 1999 vintage terminology - drop the "2", please.)
You can write a web-based address book using servlets and JSPs. If you want a relational database you can use JDBC, but it's possible to make do without that.
You should make your data access layer interface-based. That will let you change the implementation without affecting clients.
Your UI will be JSPs. You'll have a front controller servlet that will accept requests, figure out how to handle them, and send the response to the next view.
Java EE contains many technologies that can make building this type of application easier:
EJB - Use a session bean to create your application.
JAX-RS - Expose your session bean as a RESTful service via XML and JSON messsages.
JAXB - Handles the conversion of your model objects to/from XML and JSON
JPA - Handles storing your model objects in the database without you writing JDBC code
If this sounds like a lot, look at how little code you need to write:
package org.example;
import java.util.List;
import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
#Stateless
#LocalBean
#Path("/customers")
public class CustomerService {
#PersistenceContext(unitName="CustomerService",
type=PersistenceContextType.TRANSACTION)
EntityManager entityManager;
#POST
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void create(Customer customer) {
entityManager.persist(customer);
}
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("{id}")
public Customer read(#PathParam("id") long id) {
return entityManager.find(Customer.class, id);
}
#PUT
#Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public void update(Customer customer) {
entityManager.merge(customer);
}
#DELETE
#Path("{id}")
public void delete(#PathParam("id") long id) {
Customer customer = read(id);
if(null != customer) {
entityManager.remove(customer);
}
}
#GET
#Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
#Path("findCustomersByCity/{city}")
public List<Customer> findCustomersByCity(#PathParam("city") String city) {
Query query = entityManager.createNamedQuery("findCustomersByCity");
query.setParameter("city", city);
return query.getResultList();
}
}
For a Full Example
Part 1 - The Database
Part 2 - Mapping the Database to JPA Entities
Part 3 - Mapping JPA entities to XML (using JAXB)
Part 4 - The RESTful Service
Part 5 - The Client
You say you are a Java beginner, the answer to your dilemma IMO depends on your experience with other languages (and programming in general). There are alot of layers in a web application, meaning many things can go wrong, so I think it is best to start with the easy stuff and work your way up. SO... I would recommend not getting carried away with XML, JSON, MVC, etc on your first app. You can still write a great application and learn alot of stuff by keeping it a little lower tech, such as using JSP pages that use JavaBeans and letting the beans handle the SQL, etc.
You can (and should) move on from there with AJAX, MVC architectures, etc.

Spring, #WebService / #WebMethod, (using Jax-WS), receiving a serialized object?

I've been gradually piecing together how I can receive a serialized object within Spring and have gotten a web service working, by following a tutorial, that uses Jax-WS. I have verified that I can access this basic service through a browser by pulling up the XML page using a url like http://localhost:8080/WebServicesExample/hello?wsdl
The code I currently have is like below, however I want to make a service so that a serialized object can be passed in, for example a HashMap and then have spring de-serialize it, etc. I have been doing a lot of reading on this but am still a bit lost, I would appreciate if anyone can offer advice how to get from where I am at currently to what I am trying to do. Thanks
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.mkyong.bo.HelloWorldBo;
#WebService
public class HelloWorldWS{
//DI via Spring
HelloWorldBo helloWorldBo;
#WebMethod(exclude=true)
public void setHelloWorldBo(HelloWorldBo helloWorldBo) {
this.helloWorldBo = helloWorldBo;
}
#WebMethod(operationName="getHelloWorld")
public String getHelloWorld() {
return helloWorldBo.getHelloWorld();
}
}
I am not completely sure which WS stack you have used for exposing this service, assuming that you just want to create a JAX-WS based sample, let me point you to a working sample that I had created earlier available at : git://github.com/bijukunjummen/memberservice-codefirst.git .
This sample uses Apache CXF as the JAX-WS implementation, and uses JAXB2 for binding (converting the incoming xml to Java objects and back)
In your example, Apache CXF would allow you to expose a WS interface using an entry into spring configuration files of the type:
<jaxws:endpoint address="/helloworldservice" id="helloworld" implementor="#helloworldBean" >
</jaxws:endpoint>

JBoss Web Services interoperability with ASP.NET

I have a Web Service deployed on JBoss 4.2.3. The Web Service is created using the EJB3 #WebService annotation. One of the method requires an object which has a java.util.Date property
public void createUser(UserDTO dto) throws FancyException{
//-- do some work here
}
class UserDTO {
.....
private Date joined;
//-- appropriate setters
}
I have 2 clients, Axis generated client and ASP.NET generated client.
Calls from the Axis client are Ok, i.e. the date object has the value set by the client.
Calls from the ASP.NET client do not send the date set by the client, i.e. joined is null.
Non primitive datatypes have the option of being nullable, maybe for performance reasons. An extra boolean property propertySpecified is added that will instruct ASP.NET to include the attribute when serializing it down the wire. By setting this to true the corresponding variable is serialized as well.
Included are some links you might find useful on the same subject.
Another way would be to make sure the attributes are required.

Categories