Overwrite toString() method in a Java class

  • The wrapper classes like ‘Integer’, ‘Double’, ‘Float’ will be having ‘toString()’ method in their classes. Implementation in that method is like they take input as respective type and return String value.
    eg: Integer i = 10;
    String ival = i.toString();
    Note that toString() method has the code to convert Integer to String.
  • You can not overwrite the toString() method of Integer class or any other wrapper classes. [you can’t extend Integer class as it is declared as Final. So you can not overwrite its toString() method. This applies to all wrapper classes.]
  • If you want to store your class object as key in map. you can do it, but when you try to print the keys present in the Map then it’ll return the hashcode of address where the class object stored in hash memory, instead returning exact key. So you need to overwrite the ‘toString()’ method to give your own implementation. By default toString() method returns hashcode, so by overwriting this method in your class you can return any value for the class object instead of its hashcode.
  • Check the below Java code.

package model;

import java.util.HashMap;
import java.util.Map.Entry;

public class Price {

int itemsCount;
String itemName;

Price(int item, String name) {
this.itemsCount = item;
this.itemName = name;
}

public static void main(String[] args) {
HashMap<Price, String> hm = new HashMap<>();
hm.put(new Price(10, "Oranges"), "Fruit Orange");
hm.put(new Price(20, "Mangos"), "Fruit Mango");
hm.put(new Price(30, "Bananas"), "Fruit Banana");
hm.put(new Price(30, "Grapes"), "Fruit Grapes");

for (Entry<Price, String> entry : hm.entrySet()) {
System.out.println("Key:" + entry.getKey() + " & Value:" + entry.getValue());
}

}

@Override
public String toString() {
return this.itemName+this.itemsCount;
//return "ravi";
}

}

 

Output if you don’t overwrite the toString() method:

Key:model.Price@7852e922 & Value:Fruit Banana
Key:model.Price@15db9742 & Value:Fruit Orange
Key:model.Price@6d06d69c & Value:Fruit Mango
Key:model.Price@4e25154f & Value:Fruit Grapes

Output after overwriting the toString() method:

Key:Bananas30 & Value:Fruit Banana
Key:Oranges10 & Value:Fruit Orange
Key:Mangos20 & Value:Fruit Mango
Key:Grapes30 & Value:Fruit Grapes

// If you return ‘ravi’ in toString() method then it’ll return ‘ravi’ as key for all records.

 

 

 

 

 

Implement Auto suggest in JSP using Ajax call in Jquery

This solution is: When user enters any data on the input field, the entered data is taken and using ajax call servlet method will be triggered, which returns the matched records in DB as JSON string. Then the response data will be shown as suggestion under input text field.

Files Created to implement this functionality:

autoSuggest.jsp, searchServlet.java.

Code for autoSuggest.jsp:


<!DOCTYPE html>
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
         <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
  var val = $("#project").val();
  var projects;

    $( "#project" ).autocomplete({
      minLength: 1,
      source: function( request, response ) {
       $.ajax({
            type: "Get",
            url:"searchservlet",            
            contentType : "application/json", dataType : 'json',
            data:{"empName":$("#project").val()},
            success: function(data){
                projects = data;
                response(data);
            },
            failure: function(){
                alert("failed..");
            }
         });
      },
      focus: function( event, ui ) {
        $( "#project" ).val( ui.item.EmpName );
        return false;
      },
      select: function( event, ui ) {
        $( "#project" ).val( ui.item.EmpName );        
        return false;
      }
    })  
   
    .data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("
	<li style='font-size:16px;color:#777;padding:1px;'>")
                    .data("ui-autocomplete-item", item)
                    .append("<a> " + item.EmpName + "
 </a>")
                    .appendTo(ul);
            };
            
    /*  [This code also works similar as above [you can change the item name. But you have to use only "instance" with .autocomplete or
     * "ui-autocomplete" with .data] 
    * .autocomplete( "instance" )._renderItem = function( ul, listitem ) {
      return $( "
	<li>" )
        .append( "
<div>" + listitem.EmpName + "
" + "</div>
" )
        .appendTo( ul );        
    };*/        
  } );
  </script>
</head>
<body>
<div id="project-label">Search an Employee (type "E" for a start)::</div>
<input style="padding:10px;font-size:18px;margin:10px;" id="project">
<!--<input type="hidden" id="project-id"> -->
</body>

</html>

searchServlet.java


package model;

import java.io.IOException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@WebServlet(name = "searchServlet", urlPatterns = { "/searchservlet" })
public class searchServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("entered servlet...");
String empName = request.getParameter("empName").concat("%");
System.out.println("request value:"+empName);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
PreparedStatement ps = conn.prepareStatement("select empname from emp where empname like ? order by empname");
ps.setString(1, empName);
ResultSet rs = ps.executeQuery();
JSONArray jarray = new JSONArray();

int i =1;
while(rs.next()){
JSONObject jobj = new JSONObject();
String lable = "EmpName";
jobj.put(lable, rs.getObject(1));
jarray.add(jobj);
i++;
}

String JsonString = jarray.toJSONString();
System.out.println("JsonString:"+JsonString);
conn.close();
response.getWriter().write(JsonString);
} catch (Exception e) {
}

}
}

 

UI Page:

3

 

 

 

 

 

Ajax Call in JSP to fetch and display data from Database

We knew that with the help of JQuery we can dynamically display data on a webpage. So here in this post we are using  JQuery to make an Ajax call to Servlet, [Servlet connects to DB, fetches data and returns that data to Ajax call] and display the returned data as a table on JSP web page.

Create Servlet first

Create dataServlet.java

package model;

import java.io.IOException;
import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

import org.eclipse.persistence.oxm.json.JsonArrayBuilderResult;
import org.eclipse.persistence.oxm.json.JsonGeneratorResult;
import org.eclipse.persistence.oxm.json.JsonObjectBuilderResult;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@WebServlet(name = "dataServlet", urlPatterns = { "/dataservlet" })
public class dataServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=windows-1252";

public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("enterred servlet...");
String empID = "";
try {
empID = request.getParameter("empID");
System.out.println("empID is:" + empID);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
PreparedStatement ps = con.prepareStatement("select * from emp where empid != ? order by empid");
ps.setString(1, empID);
ResultSet rs = ps.executeQuery();
System.out.println("got response....");

JSONArray json = new JSONArray();
ResultSetMetaData metadata = rs.getMetaData();
int numColumns = metadata.getColumnCount();

while (rs.next()) //iterate rows
{
JSONObject obj = new JSONObject(); //extends HashMap
for (int i = 1; i <= numColumns; ++i) //iterate columns
{
String column_name = metadata.getColumnName(i);
obj.put(column_name, rs.getObject(column_name));
System.out.println("rs.getObject('" + column_name + "')........." + rs.getObject(column_name));
}
json.add(obj);
System.out.println("Added JSON object to JSON Array..");

}

response.setContentType("application/json;charset=UTF-8");
String jsonString = json.toJSONString();
System.out.println("jsonString:" + jsonString);
response.getWriter().write(jsonString);

Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("Status", "Success");
jsonMap.put("Rows", 100);

con.close();
} catch (Exception e) {
e.printStackTrace();
}

}
}

 

Create empData.jsp

  <!DOCTYPE html>
<%@ page contentType="text/html;charset=windows-1252"%>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
         <script type="text/javascript">
          $.ajax( {
              type : "Get", url : "dataservlet", contentType : "application/json", dataType : 'json', data :  {
                  "empID" : "31"
              },
              success : function (data) {
                  $("#mytbl").append('

<tr id="headerRow"></tr>

');
                 /* In below function you can take data[any row number] data[0].
                    (a, b) are (key, value) for 0th json object. as we are shoiwng only Keys so we used only 'a' below.
                 */
                  $.each(data[0], function (a, b) {
                      $("#headerRow").append('

<td style="padding:10px;background:orange;color:white;">' + a + '</td>

');
                  });
                 /* now we have to display data [multiple row with multiple column data].
                 * Here you have to observe one thing is we have multiple rows of data [multiple JSON objects in a JSON Array &
                 * Each JSON object contains multiple key value pairs]. So we must loop through each row and and then loop through each column[key value].
                 * function $.each(data, function(a, b) will get all JSON objects inside JSON Array, where 'a' indicates JSON object number.
                 * 'b' indicates the 'JSON object'. similarly
                 * function $.each(data[a], function(c, d) will get 'a'th JSON object, And here 'c' indicates Key where as 'd' indicates value.
                 * */
                  $.each(data, function (a, b) {
                      $("#mytbl").append('

<tr id="' + a + '"></tr>

');
                      var dataRowId = '#' + a;
                      $.each(data[a], function (c, d) {
                          $(dataRowId).append('

<td style="padding:10px;background:green;color:white;">' + d + '</td>

');
                      });
                  });
              },
              failure : function () {
                  alert("error...");
              }
          });
        </script>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
<title>first</title>
</head>
<body>
<?audit suppress oracle.ide.xml.mismatched-end-tag?>
<table id='mytbl'></table>
<div style="background:Green;width:100%;padding:5px 0px;margin:10px 0px; ">
<p style="color:#fff;margin-left:10px;"> copyrights @teja.com</p>

</div>
</body>
</html>

 

Data in the DB is like below:

1

JSON Array that the servlet returns to Ajax call will be like below.

JSON_Array.png

The JSP page will look like below.

2

How to set ‘autoComplete’ property for html:text component in struts

If you are developing your jsp page using struts then, In few cases you get a requirement that while typing in an input filed it should not show the suggestions that previously entered.

So generally to achieve this we use the property ‘autoComplete=off’ for html input fields. But struts <html:text> doesn’t support this property. So to achieve this feature in struts we have three options.

1) Use normal html input component in the place of  struts html:text component.

<input type="text" value="" autoComplete="off" size="10" maxlength="10" name="Account" />

2) Use <html:text> in the following way that you set ‘autoComplete’ like a css injection. The below method can be used to set properties for the components which are not supported by struts html by default.


<html:text size="10" maxlength="10" property="Account" styleClass="\" autoComplete=\"off" />

3) Create a class extending Form class or Text class and add a custom property in it.

4) You can think of using jQuery also.

 

Service Callout In OSB

Prerequisite: For understanding this you must have some basic knowledge on SOA as this post involves using SOA to make it more clear to understand.

Well, Service Callout in OSB is similar to Invoke activity in SOA. We use Invoke activity in SOA to trigger external services like (WS Service, DB Service, JMS Service, FTP Service etc). Similarly we use Service Callout in OSB to trigger external services.

Similarities & differences b/w Invoke & Service Callout: Both used to trigger external services, but Invoke can be used for both Synchronous& Asynchronous external services (i.e the calling external service may or may not give the response). But Service Callout is used only to trigger Synchronous external services. To trigger oneway services there is another component in OSB which is ‘Push’ which also works same as Service Callout, only difference is Push is used for triggering Oneway external services and Service Callout is used for triggering Synchronous external services. Invoke activity will be having ‘Input Variable’ and ‘Output variable’ and similarly Service Callout will also has ‘Request Variable’ & ‘Response Variable’.

Let’s take a simple example and discuss about why and where we use Service Callout in OSB. I’ve a an external service asynchronous  service ‘EmployeeInfo’ which accepts EmployeeId, EmployeeName as inputs.

  1. So in OSB first we have to import Resources (WSDL, XSD) for that external WSDL service. Then we have to create Business Service calling the ‘EmployeeInfo’ WSDL.
  2. Create a proxy service based out of Business Service created earlier.
  3. Now we have to pass ‘EmployeeId’, ‘EmployeeName’ as inputs the proxy service which will pass the same as inputs to the business service. But let’s make a requirement like we pass only ‘EmployeeId’ as input to the proxy service then in the Message Flow we have to call another external service ‘EmployeeName’ wsdl, passing ‘EmployeeId’ to get the respective ‘EmployeeName’ and then pass this retrieved ‘EmployeeName’ along with ‘EmployeeId’ to the ‘EmployeeInfo’ wsdl.
  4. So we have to create another Business Service calling ‘EmployeeName’ wsdl.
  5. From the MessageFlow using Service Callout call the ‘EmployeeName’ wsdl. While calling that service pass the ‘EmployeeInfo->EmployeeId’ to the ‘EmployeeName Request variable’ using Assign activity.
  6. Get the response from ‘ EmployeeName Response variable’ and replace it on ‘EmployeeInfo->EmpName’ using Replace activity. This concept is called Message Enrichment.

This is how and why Service Callout is used in OSB. Find below few screnshots for your reference.

The below screen explains about service callout variables (similar to Invoke activity input, output variables)

Note: In all the below screens please assume Customer as Employee.

ServiceCallout

Below screen explains about how we assign ‘EmployeeInfo->EmployeeId’ to ‘EmployeeName request variable’ with the help of Assign.

Assign

Below screen explains about how we replace the EmployeeInfo payload, ‘EmployeeInfoBS->EmployeeName input field’ to ‘EmployeeNameBS response variable’ with the help of Replace.

Replace

To make the above example work we need two SOA services ‘EmployeeInfo’ (Asynchronous) and ‘EmployeeName’ (synchronous) to be created and deployed on server. Which then have to be used in OSB project for creating business services.

Find below screens for SOA BPEL for EmployeeInfo’ (Asynchronous)

EmployeeInfoProcess

Find below screens for SOA BPEL for ‘EmployeeName’ (synchronous).

EmployeeNameProcess

Hope this post helps you to understand concept of Service Callout in OSB.

OSB 11g Installation (Software Required for Setup and links to download)

For complete set up of OSB we need to install multiple software on our machine and this post put all the necessary information for that here.

The below information is specific to Windows OS 64 bit machine.

1) Download JDK 6 and install
http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html

2) Download Oracle DB 11g XE and Install (while configuration remember password given)
http://www.oracle.com/technetwork/database/database-technologies/express-edition/downloads/index.html

3) Download RCU 11.1.1.7.0 and Install (Give DB credentials as username:sys, password: pwd given while DB installation, host: localhost, port:1521, service: XE) & in in step check the SOA & BPM Infrastructure checkbox as we need those schema only)
http://www.oracle.com/technetwork/middleware/soasuite/downloads/soasuite11gdownload-2210918.html

4) Download weblogic server 10.3.6 generic . It is available in three locations given below.
http://www.oracle.com/technetwork/middleware/soasuite/downloads/soasuite11gdownload-2210918.html [10.3.6 Size: 0.99 GB] (or)
http://www.oracle.com/technetwork/middleware/service-bus/downloads/index.html (or)
http://www.oracle.com/technetwork/middleware/weblogic/downloads/wls-main-097127.html [Generic (997 MB) ]

Note: While Installation you have to specify Middle ware directory, remember that.

5) Download OEPE 11.1.1.8 (oepe-indigo-win64.zip) and place the extracted folder into the Middlware folder created in earlier step.
http://www.oracle.com/technetwork/developer-tools/eclipse/downloads/oepe-11118-521475.html

6) Download Oracle Service Bus Generic (Release 11gR1 (11.1.1.7.0)
http://www.oracle.com/technetwork/middleware/service-bus/downloads/index.html

After download open the OSB installer file and go to win64 installer. Run the installer (double click on it). It will ask for JDK path, provide the JDK path and it launch the installation wizard.

e.g. D:\Softwares\Fusion\ofm_osb_generic_11.1.1.7.0_disk1_1of1\Disk1\install\win64

e.g: C:\Program Files\Java\jdk1.6.0_45

Domain Setup: Once you are done with above installations then you need to do a domain creation/ configuration.

Windows -> All Programs -> oracle weblogic -> Weblogic Server 11gr1-> Tools -> Configuration Wizard.

I hope this post helps you to set up OSB 11g on your machine. If you have any doubts feel free to post in the comment section.