Friday, 10 November 2017

Creating a directory and donwnload the files from application


Create Directory Path under the Properties File: 
Under this file path keep some pdf or tif documents for reading and downloading.

Application.properties:

                                NEW_FILE_PATH = c:/Files

Add below code in your java file:

String filesPath = resourceBundle.getString("NEW_FILE_PATH");
StringBuilder stringBuilder = new StringBuilder();
         File dir = new File(filesPath);
         String[] filenames = null;
        if (dir != null && dir.listFiles()!= null) {
           
            filenames= dir.list();
                      
            for(int i=0;i<filenames.length;i++){
               
                fileList.add(filenames[i]);
            }
    }


Once Get the filenames from Directory We need to show the files in the frontEnd, So:
Add the Div to StringBuilder and construct the file to showing on UI.




 if(filenames != null && filenames.length > 0)
         {
        
                 stringBuilder.append("<div class=\"file_display\">")
                 .append("<div class=\"files\">");
                 for(int i=0;i<fileList.size();i++) { 
                         String fileName = "";
                         fileName = fileList.get(i);
                         System.out.println("fileName::"+fileName);
                         checkPDFFile(fileName,stringBuilder,auditLoanCaseID);
                }
                 stringBuilder.append("</div></div>");
         }
return stringBuilder.toString();


private void checkPDFFile(String fName, StringBuilder sb,String auditLoanCaseID)
    {
        if(fName.endsWith(".PDF") || fName.endsWith(".pdf")){
            log.info("Checking the File extension ::" + fName);
            sb.append(HREF);
            sb.append("#");
            sb.append("\" ");
            sb.append(" onClick=\"javascript:downloadLoanCaseDoc('"+fName+"','"+auditLoanCaseID+"' )\">");
            sb.append("<img src=\"images/PDF_doc.png\"><span>");
            sb.append(fName);
            sb.append(SPAN);
            log.info("final fName value :::"+fName);
            log.info("final fName value :::"+sb);
         }
        else{
           log.info("Checking the File extension in Other Files::" + fName);
                sb.append(HREF);
                sb.append("#");
                sb.append("\" ");
                sb.append(" onClick=\"javascript:downloadLoanCaseDoc('"+fName+"','"+auditLoanCaseID+"')\">");
                sb.append("<img src=\"images/images.png\"><span>");
                sb.append(fName);
                sb.append(SPAN);
         }
       
    }

Now Write Script method and call the action class for downloading the file.

function downloadLoanCaseDoc(docName, loanCaseId) {
    var url = "downloadLoancaseIdDocuments.action?docName="+docName;
    window.open(url,'edit','scrollbars=yes,width=415,height=365');
}

Action class :

public void downloadLoancaseIdDocuments(){
       
        HttpServletResponse  httpRes = ServletActionContext.getResponse();
        ResourceBundle resourceBundle = ResourceBundle.getBundle("resource.application");
        response.setContentType("application/octet-stream");
        response.setHeader("Cache-control","public");
        response.setHeader("Content-Disposition","inline; filename="+docName);
       
        ServletOutputStream serveltOutputStream = null;
        File file = null;
        FileInputStream fis = null;
        int length = 0;
        try {
           
            serveltOutputStream = httpRes.getOutputStream();

            String filesPath = resourceBundle.getString("NEW_FILE_PATH");
            file = new File(filesPath);

            fis = new FileInputStream(file);

            log.info("fis.available()" + fis.available());

            byte[] buff = new byte[Constants.BYTES];

            int read = 0;

            //read file contents

            while((read = fis.read(buff))!= -1){

            serveltOutputStream.write(buff,0, read);

            }

            serveltOutputStream.flush();
           
           
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            try {
                httpRes.flushBuffer();
                serveltOutputStream.close();
                log.info("downloadLoanCaseIdDocuments Ends....");
            } catch (Exception e2) {
                // TODO: handle exception
            }
           
        }
    }


Tuesday, 14 February 2017

WebServices

WebServices : To communicate two systems through networks.


SOAP : Simple Object Access Protocol based on XML it will process the services.
REST : REpresentational State Transfer can access over the networks.


Types of web services : 

There are two types of web services:

JAX-RPC based web services, in which a Service Provider publishes the service definition using a Web Services Definition Language (WSDL) and the Service Consumer sends a serialized XML message wrapped in a SOAP envelop across the wire.

JAX-RS based web services, in which a Service Provider publishes the Resource name that can be used to consume the service, and the Service Consumer uses stateless operations from the HTTP protocol and sends requests and receives response messages. Because of the stateless nature of the operations, web services are called Representational State Transfer (REST) services. The message payload can either be in XML or JSON format.

SOAP
REST
            1.   SOAP stands for simple object  standard protocol.
      1.  Rest follows Representational Architecture.
2. SOAP Permits only XML based data.
2. Rest accepts JSON, Text, XML and HTML data.
3. SOAP can’t use Rest services
3. Rest can use the SOAP Services.
4. SOAP uses Service interface to expose the logic.
4. Rest uses URI to expose the Business logic.


SOAP Webservices :
Proc      : 1. WSDL Doc provides Technical document to the client application.  
               2. Uses xml data as payload so we can easily read & access the data.

Cons     :  1. Tightly coupled with client & server.
               2. Otherthan xml formats wont work.
               3. Slow
               4. Can't be tested in other browsers.


Restful Webservices :

Adv       : 1. Light weight
               2. Loosely coupled
               3. Can tested in browsers.
               4. Fast compare to SOAP.

Dis Adv : 1. Sessions cant be maintained
               2. Since its uses http protocal, there cant be asynchronous calls.


Rest Methods : 

@GET     : Uses to fetch the data 
@POST   : Uses to create a resource and post (Save) the data.
@PUT     : Uses to update existing resource and save the data.
@Delete : Used to delete the resource or data.
@Path    : Used to find the resource path.(Class level or method level)
@RequestParam: Used to send the request from controller. (Spring based annotation)
@QueryParam : Used to send the optional parameters to the method.
@PathParam : Used to send the mandatory parameters to the method.


Session maintenance : 

As per the REST architecture, a RESTful Web Service should not keep a client state on the server. This restriction is called Statelessness. It is the responsibility of the client to pass its context to the server and then the server can store this context to process the client's further request. For example, session maintained by server is identified by session identifier passed by the client.

Gson :

Gson is a class which is providing by Google to convert the Java objects to Json and vice versa.

Parsing Json to Java Objects :
By using fromJson(Json json, Object T) we can parse the json to object.

Parsing Java Object to Json :
By using toJson(Object T) we can parse the Java object to json.

Pretty Printing :
new Gson() prints compact Json. To format the into more readable in a text editor we will use Pretty Printing like below.
Gson gson = new GsonBuilder().setPrettyPrinting().create();


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);
       }
   });

Omniroute step by step setup

 Omniroute step by step setup Step 1 : Install node js and omniroute using below command.  npm install -g omniroute Step 2 : Start the ser...