IT Certificaions

Google Cloud Platform

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

Tuesday, November 3, 2015

MS SQL Server : How to remove duplicate text in a csv String in table

Here is the function which will return string after removing duplicate text from a csv cell value.

create function dbo.RemoveDuplicateTextInCSVString(@SOURCE_STR varchar(50))
returns varchar(50)
as
begin  
  declare @TEMP_STR varchar(50)
  declare @WORD_STR varchar(50)

  set @TEMP_STR = ','

  while len(@SOURCE_STR) > 0
begin
print '--------------------'
set @WORD_STR = left(@SOURCE_STR, charindex(',', @SOURCE_STR+',')-1)+','
print '@WORD_STR :'+ @WORD_STR
if charindex(','+@WORD_STR, @TEMP_STR) = 0
begin
set @TEMP_STR = @TEMP_STR + @WORD_STR
print '@TEMP_STR : '+@TEMP_STR
end
else
print 'found duplicate, remove this..'

set @SOURCE_STR = stuff(@SOURCE_STR, 1, charindex(',', @SOURCE_STR+','), '')
print '@SOURCE_STR '+@SOURCE_STR
  end
  return @SOURCE_STR
end

Thursday, October 29, 2015

Collection holds value as a refernce in java

Value as a Reference example : Here we are fecthing a list from a collection and updating this which leads to automatic update of Map because numList is directly referring to  testmap.
-----------------------------------


public class ValueAsReference{

enum EvenOdd{
EVEN,ODD
}
public static void main(String ... arg){

Map<String,List<String>> testmap=new HashMap<String, List<String>>();
for(int i=0;i<20;i++){
String key="";
if(i%2 ==0){
key=""+EvenOdd.EVEN;

}else{
key=""+EvenOdd.ODD;
}
List<String> numList=testmap.get(key);

if(numList==null){
numList=new ArrayList<String>();
numList.add("i="+i);
testmap.put(key, numList);
}else{
numList.add("i="+i);
}
}
for(String key : testmap.keySet()){
System.out.println("key : "+key);
System.out.println(testmap.get(key));
}

}
}
--------------------------------------
Output :
key : EVEN
[i=0, i=2, i=4, i=6, i=8, i=10, i=12, i=14, i=16, i=18]
key : ODD
[i=1, i=3, i=5, i=7, i=9, i=11, i=13, i=15, i=17, i=19]


Monday, October 19, 2015

Google App Engine deleted default GCS bucket. Is there a way to restore it?

No, there is no way to restore a deleted bucket or object inside a bucket. DELETE operation comes under strong global consistency. Keep in mind that you can use Google Cloud Storage only after enabling billing for your project. It's not free.

You can go through Cloud storage documentation 

Bucket will be deleted permanently. You can see google documentation. Although a bucket will be deleted only if it is empty, means you have to delete all objects first and then you can delete an empty bucket. Choose bucket carefully as these are unique globally and can not be nested like folders or directories.

Friday, August 28, 2015

Set your application context path in Tomcat 7

Set Context path in Tomcat 7 or more using catalina.properties file,

Step 1)
Add following lines to catalina.properties file under <tomcat-install dir>/conf directory,

#myApp war file version
myApp .war=myAppLive -1.0.0.1.war
myApp .path=/myAppLive

#application deployment location
appBase=webapps

Step 2)
Now update context path in <Host> node in server.xml file in same location,
<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="false">
...
....  
 <Context path="${myApp .path}" docBase="${catalina.base}/${appBase}/${myApp .war}"/>
...
....

</Host>