IT Certificaions

Google Cloud Platform

Tuesday, August 8, 2017

Thursday, May 25, 2017

Create java client from WSDL for Google App engine

This post will explain how to consume SOAP based web services on Google App Engine platform.

  1. Keep your wsdl files in resources/wsdl folder
  2. Make these files entry in appengine-web.xml like
  3.   <static-files>
           <include path="/**.wsdl"/>
         <include path="/**.WSDL"/>
     </static-files>
  4.  Now update POM file for wsdl to java plugin
 <plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>3.0.1</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <configuration>             
                <sourceRoot>${basedir}/src/main/java</sourceRoot>
                <wsdlOptions>
                    <wsdlOption>
                          <wsdl>src/main/resources/wsdl/ReadData.wsdl</wsdl>  
                          <wsdlLocation>https://${appengine.app.id}.appspot.com/wsdl/ReadData.wsdl</wsdlLocation>
                          <extraargs>
                                 <extraarg>-p</extraarg>
                                 <extraarg>com.example.ws.readdata</extraarg>
                          </extraargs>                                      
                    </wsdlOption>
                    <wsdlOption>
                        <wsdl>src/main/resources/wsdl/SaveData.wsdl</wsdl>
                        <wsdlLocation>https://${appengine.app.id}.appspot.com/wsdl/SaveData.wsdl</wsdlLocation>
                        <extraargs>
                                <extraarg>-p</extraarg>
                                <extraarg>com.example.ws.savedata</extraarg>
                         </extraargs>
                    </wsdlOption>
                   
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>







Now you can use maven commands mvn clean install and stubs will be generated in com.example.ws.savedata and com.example.ws.readdata packages.
 

Convert pfx file into jks using java

This is a post which shows how to convert pfx file into jks.

Prerequisites : Java 6+
Step 1: Use cmd with java in your classpath

keytool -importkeystore -srckeystore testKey.pfx -srcstoretype pkcs12 -srcalias <myAliasName>
 -destkeystore jksFile -deststoretype jks -deststorepass password -destalias <alias>

Java Client with certificate authentication to access SOAP Webservice

This is an example to explain  how to authenticate java stub client with certification and send request to SOAP WSDL.

public static void applyCertificateAuthentication(MyWsdlDataRequest wsdlClientRequest)
            throws Exception {


       String keyStoreLocation="resources/keys/testKey.jks";

       String password="key@12345";
        ClassLoader classLoader = this.class.getClassLoader();
        InputStream keyInputStream = classLoader.getResourceAsStream(keyStoreLocation);

        SSLContext sc = SSLContext.getInstance("SSLv3");
        KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keyInputStream, password.toCharArray());
        factory.init(keyStore, password.toCharArray());
        sc.init(factory.getKeyManagers(), null, null);
             


        MyWsdlService serviceImpl = new MyWsdlService ();
       MyWsdlDataStub servicePort = serviceImpl.getPort(MyWsdlDataStub .class);               BindingProvider bp = (BindingProvider) servicePort;

((BindingProvider) servicePort).getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
                            sc.getSocketFactory());

 
 MyWsdlDataResponse response = servicePort.siSaveSocDataOut(wsdlClientRequest);

    }

Monday, August 8, 2016

Configure MDC with SLF4j Logback file in java

This article is all about how you configure MDC logs with SLF4J and logback.

1. Maven POM dependencies: Please add maven dependencies as given below.

       <!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
</dependency>

2. Configure logback.xml file

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="30 seconds">

<property name="DEV_HOME" value="c:/logs" />
    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>

    
    <appender name="FILE-THREAD" class="ch.qos.logback.classic.sift.SiftingAppender">
        <discriminator>
<key>logFileName</key>
<defaultValue>head0</defaultValue>
 </discriminator>
 <sift>
<appender name="FILE-${logFileName}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${DEV_HOME}/mdc.log</file>

<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %level %logger{35} - %msg%n
</Pattern>
</encoder>

<rollingPolicy
class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<FileNamePattern>${DEV_HOME}/mdc.%i.log.zip
</FileNamePattern>
<MinIndex>1</MinIndex>
<MaxIndex>10</MaxIndex>
</rollingPolicy>

<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
 </sift>
</appender>


<appender name="FILE_APPENDER" class="ch.qos.logback.core.FileAppender">
<file>${DEV_HOME}/mdc.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%X{clientName}, [%thread], %-5level %logger{36} - %msg%n
</Pattern>
</encoder>
</appender>

    
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</Pattern>
</layout>
</appender>

<appender name="FILE-ERROR"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${DEV_HOME}/error.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} - %msg%n
</Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${DEV_HOME}/archived/error.%d{yyyy-MM-dd}.%i.log
                        </fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>

</appender>

<!-- Send logs to both console and file audit -->
   <!--  here com.example is my root package -->
<logger name="com.example" level="INFO" additivity="false">

<appender-ref ref="FILE-THREAD" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_APPENDER" />
</logger>

<root level="ERROR">
<appender-ref ref="FILE-ERROR" />
</root>


</configuration>


3. Use logging in java file

package com.example.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import org.slf4j.MDC;

@WebFilter( filterName = "mdcFilter", urlPatterns = { "/*" } )
public class MDCFilter implements Filter {

@Override
public void destroy() {

}

@Override
public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain )
throws IOException, ServletException {

// Get the parameter value.
final String parameter = request.getParameter( "clientName" );

// Put it in the MDC map.
MDC.put( "clientName", parameter );

try {
chain.doFilter( request, response );
} finally {
// When the control returns to the filter, clean it.
MDC.remove( "clientName" );
}
}

@Override
public void init( final FilterConfig filterConfig ) throws ServletException {

}

}

 4. You can also use slf4j logger

package com.example.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

.....
.....

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;


@Controller
public class UserController {

private static Logger logger=LoggerFactory.getLogger(UserController.class.getName());


@RequestMapping(value = "/rest/registerUser", method = RequestMethod.POST)
    public  @ResponseBody UserDTO registerUser(@RequestParam("name") String name, 
    @RequestParam("password") String password, @RequestParam("email") String email,
    @RequestParam("contactNumber") String contactNumber) {    


try {
logger.info("Registering user : name :"+name);
                        //TODO
} catch (Exception e) {

                           logger.error("Failed to register : Exception :"+e.getMessage());
   e.printStackTrace();
}
        
        return user;
    }
}

Thursday, July 14, 2016

Struts 1 with JSON response

You want to explore struts 1.X with ajax based application which returns JSON as a response, you can go following public repository.

https://github.com/youdhveer/struts1

Wednesday, July 13, 2016

Load csv file data into MySQL table

Suppose we have a device table along with following columns.
id(integer),device(varchar),device_data(varchar).

Now suppose you want to upload data from a device.csv file like given below.
---------------------------------------------------
"id","device","device_data"
"1","A1","this is test device, model-11"
"2","A2","this is test device, model-12"
"3","A3","this is test device, model-13"
"4","A4","this is test device, model-14"
----------------------------------------------------

Use following command to insert these values from csv file to table with casting id value from text to integer.


LOAD DATA INFILE 'D:\device.csv' INTO TABLE device 
FIELDS TERMINATED BY  ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(@id, device, device_data)
SET id= CONVERT( @id, UNSIGNED INTEGER ) ;