Friday, 23 September 2016

Spring and Restful WebServices Annotations

Spring Annotations


@RestController : Used to  load the controller in Spring.

@PropertySource : To load the Property files in the Service.
Ex : @PropertySource("classpath:service.properties")

@RequestMapping : To map the Request From Controller to Service.
Ex : @RequestMapping(value="/modulename.resourcename.methodname",method=RequestMethod.GET)

@RequestBody : Used to map the request object (POJO) into the request.

@Requestparam : used to send the request parameters into the service.

@Component : Simillar to @ Service. Provide the services in Spring.

@Transactional : Used to do the Transactions with DAO. Will Write these annotation in Service only.
Having below transaction types :
TxType : REQUIRED, REQUIRES_NEW, SUPPORTS, NOT_SUPPORTED, MANDATORY, NEVER

@Repository : Used to connect the Database tables and retrive from DB.

RestFul WebServices :


@Path : Will Find the path for providing WebServcies and Services.

@GET : Used to get the information.

@Produces : Used to Produce the formats like JSON, XML, STRING,OCTETSTREAM etc.

@Consumes :  Used to Consume the formats like JSON, XML, STRING,OCTETSTREAM etc.

@POST : Used to post the information into service.

@DELETE : Used to delete the info in service.

@PUT : Used to update the info.

@QueryParam : used to send the non mandatory fields into the service.

@PathParam : Used to send the mandatory fields into the service.

@Cacheable : Used to cache the information.


Different Types of RestTemplate Calls : 

Method 1: 

HttpHeaders headers = new HttpHeaders();
        headers.add("user-id", userId);
        headers.add("Content-Type", Constants.APPLICATION_JSON);
String serviceUrl = "http://localhost:8080/testapi";
UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(serviceUrl);
        builder.queryParam("name", name);

// http://localhost:8080/testapi?name=lokesh;

HttpEntity<String> requestEntity = new HttpEntity<>(headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(builder.toUriString(),
                    HttpMethod.GET, requestEntity, String.class);


Method 2:

RequestEntity<RequestObject> requesetEntity = null;
requesetEntity = RequestEntity.post(new URI(serviceUrl)).accept(MediaType.APPLICATION_JSON)
                    .header("user-id", userId).header("Authorization", accessToken).body(requestData);

            ResponseEntity<String> response = restTemplate.exchange(requesetEntity, String.class);



JSON Conversion : 

JsonObject bodyObj = (JsonObject) jsonParser.parse(response.getBody());
        if (bodyObj != null && bodyObj.get("data") != null) {
            studentResponse= gson.fromJson(bodyObj.get("data").toString(), StudentResponse.class);

        }


Wednesday, 23 September 2015

log4j Configuration

Step1:  Add dependency in pom.xml file.

Step2:  Need to add below logger code snippet in log4j2.xml file in your application.


Step3: Need to change as below code snippet in applicationContext.xml in your application.


 Step 4: Restart the server and check the console.

Tuesday, 16 June 2015

Struts 1 and 2 Architectures

Struts Architecture 
Step 1: User Sends the request to Action Servlet.
Step 2: Struts-config.xml contains the Actions, Forms, ActionForwards and Mappings.
Step 3: Bundle all the request into a JavaBean extends the ActionForm.
Step 4: Decides which action class invokes to process the request.
Step 5: Vallidate the data.
Step 6: Action Class process the request with the help of ModelComponent.
Step 7: The Model interacts with DB and process the request.
Step 8: Completing the request process by Action class and returns the ActionForward to the controller.
Step 9: Based on ActionForward the controller will invoke the Appropriate View.
Step 10: Response with render back to View Component.




Struts 2 Architecture 

Step 1: User sends the request to the container.
Step 2: Container call the web.xml file and get the controller name.
Step 3: Controller calls the ActionMapper and gets the action.
Step 4: Based on action it will call the Action Proxy 
Step 5: Action proxy will call the Configuration manager which in struts.xml file to get the info of action.
Step 6: Action Proxy process the request to Action Invocation.
Step 7: Action Invocations invokes all Interceptors and call the Action.
Step 8: Based on Action result (Response) will generate through the Action Invocation.
Step 9: Through the HttpServletResponse will sent the result to the End user.











Wednesday, 7 January 2015

JDBC Connection Steps

Jdbc Connection: 
Step 1: Loading the driver
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Step 2: Preparing the Connection String
            String cs = "jdbc:odbc:dsnName";
Step 3: Request for the connection
            Connection con = DriverManager.getConnection(cs,"username","password");
Step 4: Perform the dml operations
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery("select * from Employee");
Step 4: Storing the Results in Result Set
            while(rs.next())
            { rs.getInt(1); rs.getString(2);rs.getDouble(3);}
Step 5: Close the all open connections.
             rs.close(); st.close(); con.close();

PreparedStatement in JDBC:
Step 1 & 2 & 3 are same
Step 4: PreparedStatement is used to store the data dynamically. We can execute the SQL statements             multiple times using paramaterized statements.
            String insertps = con.prepareStatement("insert into Employee values(?,?,?)");
            String updateps = con.prepareStatement("update Employee set name = ?, address = ?, salary                =?");
            String deleteps = con.prepareStatement("delete Employee where salary =?");
            String selectps = con.prepareStatement("select * from Employee where EmpNo = ?");
Step 5: For all above statements set the parameters using setXXX and send
            insertps.setString(1,EmpNo);
            insertps.setString(2,Address);
            insertps.setDouble(3,Salary);
Step 6: Like above we can delete and update all the PreparedStaments.
Step 7: Finally Close the connections.




Sunday, 22 December 2013

Ajax calling using Jquery

Step 1 : In Jsp, use id's and class's and use in under js file
class name = processID
url : action URL
data : Parameters

Step 2: js file written as,
























$(document).ready(

function () {
   $(".processID").live("click", function () {
       processID = $('input[name="filterProcess"]:checked').attr('id');

       $.ajax({
           url: "performProcess",
           data: "processId=" + processID,
           cache: false,
           success: function (data) {

               document.getElementById("category").innerHTML = data;
               $("#c1").html(down);
               $("#c2").html(down);
               $("#c3").html(down);
               $("#c1Sub").hide();
               $("#c2Sub").hide();
               $("#c3Sub").hide();
           }
       });

   });

$("#categoryCheck1").live("click", function () {
       if ($(this).attr('checked')) {
           $(".c1Set").attr('checked', true);
       } else {
           $(".c1Set").attr('checked', false);
       }
   });
   $("#categoryCheck2").live("click", function () {
       if ($(this).attr('checked')) {
           $(".c2Set").attr('checked', true);
       } else {
           $(".c2Set").attr('checked', false);
       }
   });
   $("#categoryCheck3").live("click", function () {
       if ($(this).attr('checked')) {
           $(".c3Set").attr('checked', true);
       } else {
           $(".c3Set").attr('checked', false);
       }
   });
   /** *******************END*************************** */
   $("input").live("click", function () {
       var c1Count = $("#hiddenC1").val();
       var c2Count = $("#hiddenC2").val();
       var c3Count = $("#hiddenC3").val();
       var value = 0;
       value = $('input[name="c1"]:checked').length;
       if (value == c1Count) {
           $("#categoryCheck1").attr('checked', true);
       } else {
           $("#categoryCheck1").attr('checked', false);
       }
       value = $('input[name="c2"]:checked').length;
       if (value == c2Count) {
           $("#categoryCheck2").attr('checked', true);
       } else {
           $("#categoryCheck2").attr('checked', false);
       }
       value = $('input[name="c3"]:checked').length;
       if (value == c3Count) {
           $("#categoryCheck3").attr('checked', true);
       } else {
           $("#categoryCheck3").attr('checked', false);
       }
       value = $(".c1Set:checked").length + $(".c2Set:checked").length + $(".c3Set:checked").length;
       if (value != 0) {
           $("#completenessCheck").attr("disabled", true);
       } else if (value == 0) {
           $("#completenessCheck").attr("disabled", false);
       }
   });

Tuesday, 26 November 2013

Conversions into Different Formats


Date Conversion:

public Date stringToDate(String dateString) throws ParseException {
        if (dateString.trim() == null || "".equalsIgnoreCase(dateString.trim())) {
            return null;
        } else {
            java.util.Date date = null;
            date = new SimpleDateFormat("MM/DD/yyyy", Locale.ENGLISH)
                    .parse(dateString);
            return new Date(date.getTime());
        }
    }

String to Float Conversion :

    public float stringToFloat(String value) throws ParseException {
        String sValue = value.trim();
        sValue = sValue.replaceAll(",", "");
        float returnValue = 0;
        if (sValue == null || "".equalsIgnoreCase(sValue)) {
            return returnValue;
        } else {
            returnValue = Float.parseFloat(sValue);
            return returnValue;
        }
    }


String to Double Conversion:

public double stringToDouble(String value) throws ParseException {
        String sValue = value.trim();
        sValue = sValue.replaceAll(",", "");
        double returnValue = 0;
        if (sValue == null || "".equalsIgnoreCase(sValue)) {
            return returnValue;
        } else {
            returnValue = Double.parseDouble(sValue);
            return returnValue;
        }
    }

Monday, 25 November 2013

Browser Compatible Issues & Script issues solutions




Z-index:

Adding z-index:
The first example, Stacking without z-index, explains how stacking is arranged by default. If you want to specify a different stacking order, you have to position an element and use the z-index property.
This property is assigned with an integer value (positive or negative), which represents the position of the element along the z-axis. If you are not familiar with the z-axis, imagine the page has several layers one above the other. Each layer is numbered. A layer with a greater number is rendered above layers with smaller numbers.
Warning! z-index only has an effect if an element is positioned.
  • bottom: furthest from the observer
  • ...
  • Layer -3
  • Layer -2
  • Layer -1
  • Layer 0 default rendering layer
  • Layer 1
  • Layer 2
  • Layer 3
  • ...
  • top: closest to the observer
Notes:
  • When no z-index property is specified, elements are rendered on the default rendering layer 0 (zero).
  • If several elements share the same z-index value (i.e. they are placed on the same layer), stacking rules explained in the section Stacking without z-index apply.
In the next example, the layers' stacking order is rearranged using z-index. The z-index of DIV#5 has no effect since it is not a positioned element.
Example source code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head><style type="text/css">

div {
   opacity: 0.7;
   font: 12px Arial;
}

span.bold { font-weight: bold; }

#normdiv {
   z-index: 8;
   height: 70px;
   border: 1px dashed #999966;
   background-color: #ffffcc;
   margin: 0px 50px 0px 50px;
   text-align: center;
}

#reldiv1 {
   z-index: 3;
   height: 100px;
   position: relative;
   top: 30px;
   border: 1px dashed #669966;
   background-color: #ccffcc;
   margin: 0px 50px 0px 50px;
   text-align: center;
}

#reldiv2 {
   z-index: 2;
   height: 100px;
   position: relative;
   top: 15px;
   left: 20px;
   border: 1px dashed #669966;
   background-color: #ccffcc;
   margin: 0px 50px 0px 50px;
   text-align: center;
}

#absdiv1 {
   z-index: 5;
   position: absolute;
   width: 150px;
   height: 350px;
   top: 10px;
   left: 10px;
   border: 1px dashed #990000;
   background-color: #ffdddd;
   text-align: center;
}

#absdiv2 {
   z-index: 1;
   position: absolute;
   width: 150px;
   height: 350px;
   top: 10px;
   right: 10px;
   border: 1px dashed #990000;
   background-color: #ffdddd;
   text-align: center;
}

</style></head>

<body>

<br /><br />

<div id="absdiv1">
   <br /><span class="bold">DIV #1</span>
   <br />position: absolute;
   <br />z-index: 5;
</div>

<div id="reldiv1">
   <br /><span class="bold">DIV #2</span>
   <br />position: relative;
   <br />z-index: 3;
</div>

<div id="reldiv2">
   <br /><span class="bold">DIV #3</span>
   <br />position: relative;
   <br />z-index: 2;
</div>

<div id="absdiv2">
   <br /><span class="bold">DIV #4</span>
   <br />position: absolute;
   <br />z-index: 1;
</div>

<div id="normdiv">
   <br /><span class="bold">DIV #5</span>
   <br />no positioning
   <br />z-index: 8;
</div>

</body></html>
See also
  • Stacking without z-index : Default stacking rules
  • Stacking and float : How floating elements are handled
  • The stacking context : Notes on the stacking context
  • Stacking context example 1 : 2-level HTML hierarchy, z-index on the last level
  • Stacking context example 2 : 2-level HTML hierarchy, z-index on all levels
  • Stacking context example 3 : 3-level HTML hierarchy, z-index on the second level



Overlay issue:
Close button wont work Some time’s :
We need to change the javascript:parent.close() method to javascript:close();
Then it wont take parent object and it will close.

Print Button Implementation:
1.            Take div for header and footer and content and for css also(what ever u want to print) and give id for the div’s.
2.            Call the javascript method or Jquery method on keydown event for print, here we need to capture the ctrl+p event also using event key (if Required)
jQuery(document).keydown(function(event) {
                  //alert('ctrl+p');
            if(event.ctrlKey && event.keyCode == 80) {
           
                   console.log("Hey! Ctrl+P event captured!");
                   event.preventDefault();
                   event.returnValue=false;
                   printCorePage();
                  }
        });
3.            First apply for css and apply for header and apply for content and apply for Footer.(content)
4.            Using, document.getElementById(“idname”).innerHTML = content
5.            If any content is not required then block the content.
                Using, document.getElementById("printmenu").style.display = "none";

UI Tips:


Importing java file into jsp:

<%@page import="com.uboc.banking.bo.UserControl"%>
-------------------------------------------------------------------------
Importing tag-lib into jsp:

<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

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

Prototype.js error :

Add jquery conflict code in jquery

$.noConflict();

($ depends upon jquery symbol)

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


Object expected: Script error

Import is missing for that variable, So import the required class


-----------------------------------------------------------------------
Object extected : Script error

Some time need to import the core matric's lib

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

To restrict the Hyperlinks in a page Code:

var div = document.getElementById("printableContentBlock");
                                var anchorList = div.getElementsByTagName('a');

                                  for(var i = 0; i < anchorList.length; i++) {
                                                anchorList[i].disabled = true;
                                                anchorList[i].onclick = '';
                                    anchorList[i].removeAttribute('href');
                                                }
                                window.print();
         window.close();
      }
----------------------------------------------------------------------------


Object expected: script error in IE

ex: firstusageconfirmpayment.do

Solution: need to import the function implementation file

Ex: Tip is not defiend in FF

Solution: Need to import the below js file :

<script language="JavaScript" src="/js/wz_tooltip<%=cacheVersion%>.js"></script>

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

Script Error: "actualTitle" is null in FF

Object expected: script error in IE

1. Check the title of landing Page
2. And change the Title div id

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




Spring AI with LLama

 Spring AI :  Step 1 : Add Spring AI dependency  <dependency> <groupId>org.springframework.ai</groupId> <artifactId...