Monday, August 19, 2013

Calling / Accessing an EJB Stateless Bean Remotely


In this tutorial we are going to see , how to call an EJB bean  remotely which is deployed in a EJB Server.We have already seen how to create a simple stateless session bean using NetBeans and how to deploy the same in the GlassFish Server , if you dont know how to do this , i will recommend please see this link   "http://ayazroomy-java.blogspot.in/2013/07/creating-simple-ejb-sessionbean-using.html ".   

We are going to access the same bean which we deployed in the previous part   "http://ayazroomy-java.blogspot.in/2013/07/creating-simple-ejb-sessionbean-using.html " , namely "HomeImpl"(Seesion Bean) with the JNDI Name "abc".

To access an EJB Bean remotely we need to follow these steps :

Note : We are note following any J2EE Pattern here for accessing EJB , there are lot of patterns available for making an EJB call which helps us to reduce the traffic,memory and other stuffs.

Step 1:

Add all the Require Jar files in the libraries.Right click on the Libraries and select add Jar and go to the GlassFish folder and select all the jars inside the "Modules" folder.

Ex :
E:\Install-files\Net\glassfish\modules

Add the Jar file "MyApp" our EJB Project jar which we have created previously, if not create it using the "clean and build" option by right clicking on the Project Node and select "Clean and Build".The jar file will be created and available inside the dist folder of the Project .

Step 2 :

Once all the Jars is added, we can write our client code to access the Bean.


Code:
 
import java.util.Properties;
import javax.naming.InitialContext;
import test.Home;
import test.MyBeanRemote;

public class Main
{

public static void main(String[] args)throws Exception { 

/*
Require EJB2.0 Version
System.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
System.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
System.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
System.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
System.setProperty("org.omg.CORBA.ORBInitialPort", "3700"); */
InitialContext ic = new InitialContext( );
Object l=ic.lookup("abc");
Home d=(Home)l;
 System.out.println(d.sayHello("Jack Sparrow..."));

}

}

Output :
Welcome to EJB Jack Sparrow...

Note : All the GlassFish jars should be added in libraries and the Bean should be deployed in the GlassFish Server otherwise an exception will occur.

This will work fine under both the GlassFish Server and client in the same System , when we tried to access the EJB Client from other System we have to specify the IPAddress & Port of the machine in which server is running  in the System.Property values.

 Thanks for Reading...

                                               Index 

   --------------------------------------------------------------------------------------------------





Technology Blogs
blogs

Wednesday, August 14, 2013

Java WebService Tutorial - Part 13 ( XML & JSON )


Producing XML and JSON:

In the previous section we have seen how to access Parameters from URL and what are useful classes we can use in our REST Services. In this section we will see how to Produce different Responses such as XML and JSON in REST.

So far in our all example, we have used GET and access directly from the Browser URL.What if some one wants to POST data , in this case i need to used POST Method, let see the following example here.

    @POST
    @Path("/Postme")
    @Produces("text/plain")
    public Response getData(@FormParam("user")String user)
    {
        return Response.ok(user).build();
    }

I cannot go directly in to the Browser and hit the URL with the Path .../Postme it will give me an error saying Method not allowed, we cannot directly do that, either we need a form to Post these changes and we need to write a client class to access this service. How to write a Client to access REST Service will be cover in later Parts. Now we will see how to do this by using a Html Form Submission.

Ex:

<form method="post" action="/....../Postme">
User :<input type="text" name="user">
<input type="submit">
</form>

When the submit button is pressed the "/Postme"Path 's respective Method get's invoked and it takes the parameter "user" which is a textfield inside the form tag ,and return the Response as the value entered in the html textfield.

As , for Producing JSON and XML we can use get or post it depend upon the criteria, now for our understanding , i am using GET to Produce  JSON and XML Data and display it to the User.

1. XML :

XML can be produce in two ways , either using the JAXB if you don't know JAXB , no need to Panic it just an API Provided by J2EE for quickly forming XML ,Parsing XML and Producing XML.

It takes some little Annotations that's it it wont take much time to understand the basics of JAXB.
Jersey , automatically does the XML /JSON Conversion, while returning response.

Another way to produce the XML is by returning as String in the Response, it is not the best way , but it can also produce XML Output.

EX:
    @Path("/check/{username}")
    @GET
    @Produces("text/xml")
    public String getText(@PathParam("username")String username) {
     return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>   <username>"+username+"</username></root>";
    }

This code will Produce the output as String in the XML Format.

 If you access from URL:  ....../check/John

Output :<root><username>John</username></root>

Using JAXB Style:

Create a Class called "Student".

package test;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement // This does everthing for Creating XML .
public class student {
private int rollno;
 private String name;
  public int getRollno() {
        return rollno;
    }
    public void setRollno(int rollno) {
        this.rollno = rollno;
    }
public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  
}

Inside the REST Service Class:

    @Path("/getXML")
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public student getXML()
    {
        student s=new student();
        s.setName("Ayaz");
        s.setRollno(1440);
        return s;
    }
Deploy the Service & Access this Method ....../getXML  will return the following Output:

XML Output :
<student><name>Ayaz</name><rollno>1440</rollno></student>

Note : Just By changing MediaType.APPLICATION_XML to
MediaType.APPLICATION_JSON in the @Produces Annotation of the Method getXML will give the following JSON Output 

JSON Output :
{"rollno":1440,"name":"Ayaz"}

2. JSON:

We have already seen the how to produce JSON output using JAXB, Now we will look at how we can do it manually using the JSON classes provided by the Jackson framework which comes along with the Jersey.
It can be done by specifying the following in the web.xml file:
          <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
              </init-param>
This enables the Jackson framework which comes along with the Jersey.Jackson used to provide the libraries to use for accessing and producing JSON.

Ex:
    @Path(“/Mydata”)
    @GET
    @Produces("application/json")
    public Response getData() throws JSONException
    {
        JSONObject jSONObject=new JSONObject();
        JSONArray array=new JSONArray();
        
       for(int i=0;i<5;i++)
       {
        jSONObject.put("name"+i, i);
          
       }
        array.put(jSONObject);
        String h=array.toString();
        Response r=null;
        r=Response.ok(h).build();
        return r;
    }

Output:
[{"name0":0,"name1":1,"name2":2,"name3":3,"name4":4}]

That's all folks , in the next section we will see how to write a REST client.

Thanks for Reading... 
Please provide your valuable comments & suggestion.


<<Prev                           Index                             Next >>

------------------------------------------------------------------------------------------ 







Technology Blogs
blogs

Tuesday, August 13, 2013

A Simple Swing Application to Load Multiple Languages (Internationalization)


Hi ,Today we are going to see how to load multiple languages in a swing application like , i have a JFrame
which contain JLabel , JRadioButton, JButton  and other fields and i have three different labels say English,
Spanish,German on clicking on these respective labels there respective language should get loaded and the
Labels ,Radio buttons and other fields name and there text should get change accordingly in they JFrame.

We can do these by the help of Properties files.

Using of Properties files :

- A Properties file have an extension .properties and read and saved as .properties.

- A Properties file have values in the form of key & value pair ex: name="Jack"

How to load different Languages:

 - For each Language we will use different Properties file example  for english - english.properties similiar for others.

- We can use java.util.Properties class to load the properties and get the key and there respective value using    the getProperty() method  .

In this example , we are going to use  the following Properties file:

english.properties
spanish.properties
german.properties

All these Properties files will have a key with the same name .

english .properties:

username=Username
password=Password
gender=Gender
male=Male
female=Female
age=Age
address=Address
submit=Submit
message=Successfully Submitted....


spanish.properties :

username=Nombre de usuario
password=contraseña
gender=género
male=macho
female=femenino
age=edad
address=dirección
submit=entregar
message=Presentada con éxito ...

german.properties :

username=Benutzername
password=Kennwort
gender=Geschlecht
male=männlich
female=weiblich
age=alter
address=Anschrift
submit=einreichen
message=Erfolgreich abgegeben ...


Now , we have the properties file ready with the key and pair value, Now we need to follow these steps:

Steps:

- Create a package called properties.

- Place all the Properties file inside this package , otherwise the properties file will not get loaded.

- Create a JFrame GUI window with some labels,textfields and buttons inside the properties package.

- After designing write a method call loadLang(String lang) which take the language as argument and loads the respective properties file.

- Write action events to load different properties.


/* For loading different Languages*/

private void loadLanguages(String lang) {
try
{
Properties p=new Properties();
p.load(loadProperties.class.getResourceAsStream(lang+".properties"));
String username=p.getProperty("username");
String password=p.getProperty("password");
String gender=p.getProperty("gender");
String male=p.getProperty("male");
String female=p.getProperty("female");
String age=p.getProperty("age");
String address=p.getProperty("address");
String submit=p.getProperty("submit");
message=p.getProperty("message");

/* Set the Values Here*/

jLabel2.setText(username);
jLabel3.setText(password);
jLabel4.setText(gender);
jRadioButton1.setText(male);
jRadioButton2.setText(female);
jLabel5.setText(age);
jLabel6.setText(address);
jButton1.setText(submit);

}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}


}
}


Full Code:

 package properties;

import java.awt.Color;
import java.util.Properties;
import javax.swing.JOptionPane;

 public class Load extends javax.swing.JFrame {
String message="";

public Load() {
initComponents();
loadLanguages("english"); // Default load english Language
setSize(600,500);
}

 
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);

  jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
jLabel1.setText("Example - Loading Mutilple Languages .....");
getContentPane().add(jLabel1);
jLabel1.setBounds(40, 10, 520, 40);

jLabel2.setText("jLabel2");
getContentPane().add(jLabel2);
jLabel2.setBounds(20, 100, 110, 20);

jLabel3.setText("jLabel3");
getContentPane().add(jLabel3);
jLabel3.setBounds(20, 140, 120, 20);

jLabel4.setText("jLabel4");
getContentPane().add(jLabel4);
jLabel4.setBounds(20, 180, 130, 20);

jLabel5.setText("jLabel5");
getContentPane().add(jLabel5);
jLabel5.setBounds(20, 220, 120, 30);

jLabel6.setText("jLabel6");
getContentPane().add(jLabel6);
jLabel6.setBounds(20, 260, 110, 30);

jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(200, 320, 160, 23);

  jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11));
jLabel7.setForeground(new java.awt.Color(255, 0, 51));
jLabel7.setText("English");
jLabel7.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel7MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jLabel7MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jLabel7MouseExited(evt);
}
});
getContentPane().add(jLabel7);
jLabel7.setBounds(40, 60, 50, 20);

  jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11));
jLabel8.setForeground(new java.awt.Color(255, 0, 51));
jLabel8.setText("Spanish");
jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel8MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jLabel8MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jLabel8MouseExited(evt);
}
});
getContentPane().add(jLabel8);
jLabel8.setBounds(130, 60, 50, 20);

  jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11));
jLabel9.setForeground(new java.awt.Color(255, 0, 51));
jLabel9.setText("German");
jLabel9.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel9MouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jLabel9MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jLabel9MouseExited(evt);
}
});
getContentPane().add(jLabel9);
jLabel9.setBounds(230, 60, 90, 20);

jRadioButton1.setText("jRadioButton1");
getContentPane().add(jRadioButton1);
jRadioButton1.setBounds(140, 180, 130, 23);

jRadioButton2.setText("jRadioButton2");
getContentPane().add(jRadioButton2);
jRadioButton2.setBounds(280, 180, 150, 23);
getContentPane().add(jTextField1);
jTextField1.setBounds(140, 100, 230, 20);
getContentPane().add(jTextField2);
jTextField2.setBounds(140, 140, 230, 20);
getContentPane().add(jTextField3);
jTextField3.setBounds(140, 230, 230, 20);
getContentPane().add(jTextField4);
jTextField4.setBounds(140, 270, 230, 20);

pack();
  }

private void jLabel7MouseEntered(java.awt.event.MouseEvent evt) {

jLabel7.setForeground(Color.BLUE);

  }

  private void jLabel7MouseExited(java.awt.event.MouseEvent evt) {

jLabel7.setForeground(Color.RED);
 
  }

  private void jLabel8MouseEntered(java.awt.event.MouseEvent evt) {jLabel8.setForeground(Color.BLUE);
  }

private void jLabel8MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseExited
jLabel8.setForeground(Color.RED); // TODO add your handling code here:
}//GEN-LAST:event_jLabel8MouseExited

private void jLabel9MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseEntered
jLabel9.setForeground(Color.BLUE); // TODO add your handling code here:
}//GEN-LAST:event_jLabel9MouseEntered

private void jLabel9MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseExited
jLabel9.setForeground(Color.RED); // TODO add your handling code here:
}//GEN-LAST:event_jLabel9MouseExited

private void jLabel7MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel7MouseClicked
loadLanguages("english");

// TODO add your handling code here:
}//GEN-LAST:event_jLabel7MouseClicked

private void jLabel9MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel9MouseClicked
loadLanguages("german"); // TODO add your handling code here:
}//GEN-LAST:event_jLabel9MouseClicked

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

JOptionPane.showMessageDialog(this, message);

// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed

private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
loadLanguages("spanish"); // TODO add your handling code here:
}//GEN-LAST:event_jLabel8MouseClicked

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Load.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Load.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Load.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Load.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Load().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
// End of variables declaration//GEN-END:variables

private void loadLanguages(String lang) {
try
{
Properties p=new Properties();
p.load(loadProperties.class.getResourceAsStream(lang+".properties"));
String username=p.getProperty("username");
String password=p.getProperty("password");
String gender=p.getProperty("gender");
String male=p.getProperty("male");
String female=p.getProperty("female");
String age=p.getProperty("age");
String address=p.getProperty("address");
String submit=p.getProperty("submit");
message=p.getProperty("message");

/* Set the Values Here*/

jLabel2.setText(username);
jLabel3.setText(password);
jLabel4.setText(gender);
jRadioButton1.setText(male);
jRadioButton2.setText(female);
jLabel5.setText(age);
jLabel6.setText(address);
jButton1.setText(submit);

}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e.getMessage());
}


}
}

Note :  Place the properties file and Java file in the same folder here under properties folder(name of the package) otherwise it wont able to load the data from properties file.

Compile :

G:\> cd  properties

G:\properties>javac *.java

G:\properties>cd..

Run :

G:\>java properties.Load


Result :























<< Prev                                Index                               

-----------------------------------------------------------------------------------------------------












Technology Blogs
blogs

Monday, August 12, 2013

Java WebService Tutorial - Part 12 ( Useful REST Annotations & Classes)


REST Annotations & Classes:

Hi, in this Section we will be discussing the different types of Annotations and some of the mostly used classes, provided by REST which can we use in our code.

First off, the most important Points we need to remember is:

REST is Web Service which performs all its Operation based upon the HTTP Methods. So it provides the following annotations.

@ GET
@POST
@PUT
@DELETE
@HEAD

If any one similar with the HTTP methods, they same they behave also here.

Some of the mostly used Annotations:

@Produces - This one we already discuss in our previous Sections, Any way it is used to produce a response to the User in based upon different MIME Types.( ex: text/html )

@Consumes - It is used to define what type of MIME or Inputs it will accepts from the Client .ex:  forms--URL--encoded.

@Context - It like the ServletContext in Servlet , it is the Jersey Framework context. It can used in many cases such as to get Header Parameters, Query parameters, Form Parameters etc.

Accessing Parameters in REST :

REST provides the following ways, the Param can be represented.

1.@PathParam
2.@QueryParam
3.@FormParam
4.@MatrixParam

1.@PathParam:

This annotation is used to get the Parameter specified in the URI using {} either from class level or Method Level.

Ex :CLASS LEVEL

@Path("/MyPath/{username}")
class MyPathResource
{
@GET
@Produces("text/plain")
public String getText(@PathParam("username"}String username)
{
return "UserName:"+username;
}
}

Access from URL :

Ayaz - Here taken as value for "username" and map to the Methods getText.Since getText does not have any path Associated with it the Jersey will automatically invokes this method.

Note: If there are more than one method specifies in the class with no path Annotation, then class will compile fine but the deployment will be fail.

EX: METHOD LEVEL

@Path("/MyPath/{username}")
class MyPathResource
{
@GET
@Produces("text/plain")
public String getText(@PathParam("username"}String username)
{
return "UserName:"+username;
}
@Path("/getText1/{text}")
@GET
@Produces("text/plain")
public String getText1(@PathParam("text"}String text)
{
return "Enter text:"+text;
}
}
Access from URL :

http://localhost:8080/MyPath/Ayaz  ---> Gives Output as UserName : Ayaz

http://localhost:8080/MyPath/getText1/HelloWorld  ---> Gives output as Enter text : HelloWorld

Note: If no value is pass for name  error will be thrown at runtime.


2. @Queryparam:

Queryparam is used to access the name and value pair enter in the URL using "?" .
It can be defined at class level and Method level; mostly it will be used in Method level. We will discuss Method level only.

Ex:

Here , name and age are the two Query parameters.

Ex:

    @Path("/MyMethod")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String Query(@QueryParam("name")String name ,
    @QueryParam("age")String  age )
    {
        return "Query Parameters"+" "+"Name:"+name+" "+"Age:"+age;
    }
Note: If no value is pass for name  error will be thrown at runtime.

3. @FormParam :

Form param is used to obtain values of the Form elements.

Ex:

  @Path("/posted")
    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public String  putJson(@FormParam("name")String name ) {    
        return name;
    }

Here, name is the name of the text field or some other field declared inside the Form tag. 
Note: If no value is pass for name null will be return.

4. @MatrixParam :

The Matrix Param is used to accept values in name & value pair unlike Query Parameter it does not need any questionmark to begin with nor any and (&)sign to specify multiple values. Multiple values can be represented using semicolon(;)

Ex:
 @Path("/MyMethod")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String  putMatrix(@MatrixParam("name")String name,@MatrixParam("age")int age)
    {
       return "Name:"+name+"Age:"+age ;
    }

Note: If no value is pass for name and age null will be return.


Useful Classes:
  •  MediaType 
  •  Response
  • JSONObject & JSONArray

1. MediaType :

This class can be used to represent the MIME Types in the form of Constants.

Ex:

@Produces (MediaType.TEXT_PLAIN)
 Equivalent to 
@Produces ("text/plain")


2. Response:

The Response class one of the widely used , it can be used to return response as text,images,files etc.Instead of being returning as String we should return the Response Object and let Jersey to do the remaining writing to the output stream and other stuffs.

Writing text Response

Ex:

    @Path("/matrix")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public Response putMatrix(@MatrixParam("name")String name,@MatrixParam("age")int age)
    {
       return Response.ok("Name:"+name+"Age:"+age).build();  
    }
 The Response.ok method takes the String as an Entity and builds it adds to the Output as response.


  Writing Image Response:

   @GET
    @Path("/getData")
    @Produces("image/jpg")
    public Response getData()
    {
        File f=new File("G:\\Icons\\en.jpg");
        Response.ResponseBuilder builder=Response.ok((Object)f);
        builder.header("Content-Disposition","attachment; filename=\"file_from_server.jpg\"");
                return builder.build();
    }
   
 3.JSONObject  & JSONArray :

The JSON Object class is used to create a list of JSON Objects. 

Ex:

        JSONObject jSONObject=new JSONObject();
        jSONObject.put("FirstName", "Jack");
        jSONObject.put("LastName", "Sparrow");
        jSONObject.put("Address", "America");
        System.out.println(jSONObject);

    Output :
    {"FirstName":"Jack","LastName":"Sparrow","Address":"America"}
   
    The JSON Array class is used to create an Array of JSON Objects.

Ex:     

       JSONObject jSONObject=new JSONObject();
        jSONObject.put("FirstName", "Jack");
        jSONObject.put("LastName", "Sparrow");
        jSONObject.put("Address", "America");
        JSONArray array=new JSONArray();
        array.put(jSONObject);
        System.out.println(array);

Output:  [{"FirstName":"Jack","LastName":"Sparrow","Address":"America"}]

Even though Jersey with JAXB, support automatic conversion or implementation of JSON and XML from simple Java Bean with setter/getters, It is good to know how to do it manually.

In the Next Part we will see how to produce XML and JSON output manually, and with Automatic Implementation Provided by Jersey along with JAXB.




Please provide your valuable comments.
Thanks for reading..



<< Prev                                              Index                                Next >>

---------------------------------------------------------------------------------------------------------










Technology Blogs
blogs