Tuesday, September 22, 2015

How to write a Serilizer or Desrilizer in Jackson json in java

import java.io.Serializable;
import java.util.Arrays;

import javax.xml.bind.annotation.XmlRootElement;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import com.varra.identity.json.annotate.ResponseJsonIgnore;
import com.varra.identity.json.serializer.AccountJsonSerializer;

/**
* @author Rajakrishna V. Reddy
* @version 1.0
*/
@XmlRootElement(name = "Account")
@JsonSerialize(using = AccountJsonSerializer.class)
public class Account implements Serializable
{
           
            /** The Constant serialVersionUID. */
            private static final long serialVersionUID = 2077532866344069471L;
           
            /** The Constant URL_PARAMS_DEFAULT_LENGTH. */
            private static final int URL_PARAMS_DEFAULT_LENGTH = 255;
           
            /** The id. */
            private int id = 0;
           
            /** The acc id. */
            private int accId = 0;
           
            /** The account name. */
            private String accountName = "";
           
            /** The company name. */
            private String companyName = "";
           
            /** The company telephone. */
            private String companyTelephone = "";
           
            /** The company web. */
            private String companyWeb = "";
           
            /** The type. */
            private String type = "";
           
            /** The admin username. */
            private String adminUsername = "";
           
            /** The admin password. */
            private String adminPassword = "";
           
            /** The admin password c. */
            private String adminPasswordC = "";
           
            /** The admin first name. */
            private String adminFirstName = "";
           
            /** The admin last name. */
            private String adminLastName = "";
           
            /** The email address. */
            private String emailAddress = "";
           
            /** The uuid. */
            private int uuid = 0;
           
            /** The admin user uuid. */
            private String adminUserUuid = "";
           
            /** The is active. */
            private boolean isActive = true;
           
            /** The approve status. */
            private int approveStatus = 0;
           
            /** The tag ids. */
            private String[] tagIds;
           
            /** The account tag. */
            private String accountTag = "";
           
            /** The tag created by. */
            private String tagCreatedBy = "";
           
            /** The enterprise. */
            private boolean enterprise;

            private String companyAddress;
           
            /**
            * Checks if is enterprise.
            *
            * @return true, if is enterprise
            */
            @JsonIgnore
            public boolean isEnterprise()
            {
                        return enterprise;
            }
           
            /**
            * Sets the enterprise.
            *
            * @param enterprise
            *            the new enterprise
            */
            public void setEnterprise(boolean enterprise)
            {
                        this.enterprise = enterprise;
            }
           
            /**
            * Gets the company address.
            *
            * @return the company address
            */
            public String getCompanyAddress()
            {
                        return companyAddress;
            }
           
            /**
            * Sets the company address.
            *
            * @param companyAddress
            *            the new company address
            */
            public void setCompanyAddress(String companyAddress)
            {
                        this.companyAddress = companyAddress;
            }
           
            /**
            * Gets the id.
            *
            * @return the id
            */
            public int getId()
            {
                        return id;
            }
           
            /**
            * Sets the id.
            *
            * @param id
            *            the new id
            */
            public void setId(int id)
            {
                        this.id = id;
            }
           
            /**
            * Gets the acc id.
            *
            * @return the acc id
            */
            public int getAccId()
            {
                        return accId;
            }
           
            /**
            * Sets the acc id.
            *
            * @param accId
            *            the new acc id
            */
            public void setAccId(int accId)
            {
                        this.accId = accId;
            }
           
            /**
            * Gets the account name.
            *
            * @return the account name
            */
            public String getAccountName()
            {
                        return accountName;
            }
           
            /**
            * Sets the account name.
            *
            * @param accountName
            *            the new account name
            */
            public void setAccountName(String accountName)
            {
                        this.accountName = accountName;
            }
           
            /**
            * Gets the company name.
            *
            * @return the company name
            */
            public String getCompanyName()
            {
                        return companyName;
            }
           
            /**
            * Sets the company name.
            *
            * @param companyName
            *            the new company name
            */
            public void setCompanyName(String companyName)
            {
                        this.companyName = companyName;
            }
           
            /**
            * Gets the company telephone.
            *
            * @return the company telephone
            */
            public String getCompanyTelephone()
            {
                        return companyTelephone;
            }
           
            /**
            * Sets the company telephone.
            *
            * @param companyTelephone
            *            the new company telephone
            */
            public void setCompanyTelephone(String companyTelephone)
            {
                        this.companyTelephone = companyTelephone;
            }
           
            /**
            * Gets the company web.
            *
            * @return the company web
            */
            public String getCompanyWeb()
            {
                        return companyWeb;
            }
           
            /**
            * Sets the company web.
            *
            * @param companyWeb
            *            the new company web
            */
            public void setCompanyWeb(String companyWeb)
            {
                        this.companyWeb = companyWeb;
            }
           
            /**
            * Gets the type.
            *
            * @return the type
            */
            public String getType()
            {
                        return type;
            }
           
            /**
            * Sets the type.
            *
            * @param type
            *            the new type
            */
            public void setType(String type)
            {
                        this.type = type;
            }
           
            /**
            * Gets the admin username.
            *
            * @return the admin username
            */
            public String getAdminUsername()
            {
                        return adminUsername;
            }
           
            /**
            * Sets the admin username.
            *
            * @param adminUsername
            *            the new admin username
            */
            public void setAdminUsername(String adminUsername)
            {
                        this.adminUsername = adminUsername;
            }
           
            /**
            * Gets the admin password.
            *
            * @return the admin password
            */
            @ResponseJsonIgnore
            public String getAdminPassword()
            {
                        return adminPassword;
            }
           
            /**
            * Sets the admin password.
            *
            * @param adminPassword
            *            the new admin password
            */
            public void setAdminPassword(String adminPassword)
            {
                        this.adminPassword = adminPassword;
            }
           
            /**
            * Gets the admin password c.
            *
            * @return the admin password c
            */
            @ResponseJsonIgnore
            public String getAdminPasswordC()
            {
                        return adminPasswordC;
            }
           
            /**
            * Sets the admin password c.
            *
            * @param adminPasswordC
            *            the new admin password c
            */
            public void setAdminPasswordC(String adminPasswordC)
            {
                        this.adminPasswordC = adminPasswordC;
            }
           
            /**
            * Gets the admin first name.
            *
            * @return the admin first name
            */
            public String getAdminFirstName()
            {
                        return adminFirstName;
            }
           
            /**
            * Sets the admin first name.
            *
            * @param adminFirstName
            *            the new admin first name
            */
            public void setAdminFirstName(String adminFirstName)
            {
                        this.adminFirstName = adminFirstName;
            }
           
            /**
            * Gets the admin last name.
            *
            * @return the admin last name
            */
            public String getAdminLastName()
            {
                        return adminLastName;
            }
           
            /**
            * Sets the admin last name.
            *
            * @param adminLastName
            *            the new admin last name
            */
            public void setAdminLastName(String adminLastName)
            {
                        this.adminLastName = adminLastName;
            }
           
            /**
            * Gets the email address.
            *
            * @return the email address
            */
            public String getEmailAddress()
            {
                        return emailAddress;
            }
           
            /**
            * Sets the email address.
            *
            * @param emailAddress
            *            the new email address
            */
            public void setEmailAddress(String emailAddress)
            {
                        this.emailAddress = emailAddress;
            }
           
            /**
            * Gets the uuid.
            *
            * @return the uuid
            */
            @ResponseJsonIgnore
            public int getUuid()
            {
                        return uuid;
            }
           
            /**
            * Sets the uuid.
            *
            * @param uuid
            *            the new uuid
            */
            public void setUuid(int uuid)
            {
                        this.uuid = uuid;
            }
           
            /**
            * Gets the account tag.
            *
            * @return the account tag
            */
            @ResponseJsonIgnore
            public String getAccountTag()
            {
                        return accountTag;
            }
           
            /**
            * Sets the account tag.
            *
            * @param accountTag
            *            the new account tag
            */
            public void setAccountTag(String accountTag)
            {
                        this.accountTag = accountTag;
            }
           
            /**
            * Gets the tag ids.
            *
            * @return the tag ids
            */
            @ResponseJsonIgnore
            public String[] getTagIds()
            {
                        return tagIds;
            }
           
            /**
            * Sets the tag ids.
            *
            * @param tagIds
            *            the new tag ids
            */
            public void setTagIds(String[] tagIds)
            {
                        this.tagIds = tagIds;
            }
           
            /**
            * Gets the tag created by.
            *
            * @return the tag created by
            */
            @ResponseJsonIgnore
            public String getTagCreatedBy()
            {
                        return tagCreatedBy;
            }
           
            /**
            * Sets the tag created by.
            *
            * @param tagCreatedBy
            *            the new tag created by
            */
            public void setTagCreatedBy(String tagCreatedBy)
            {
                        this.tagCreatedBy = tagCreatedBy;
            }
           
            /**
            * Checks if is active.
            *
            * @return true, if is active
            */
            public boolean isActive()
            {
                        return isActive;
            }
           
            /**
            * Sets the active.
            *
            * @param isActive
            *            the new active
            */
            public void setActive(boolean isActive)
            {
                        this.isActive = isActive;
            }
           
            /**
            * Gets the approve status.
            *
            * @return the approve status
            */
            public int getApproveStatus()
            {
                        return approveStatus;
            }
           
            /**
            * Sets the approve status.
            *
            * @param approveStatus
            *            the new approve status
            */
            public void setApproveStatus(int approveStatus)
            {
                        this.approveStatus = approveStatus;
            }
           
            /**
            * Gets the admin user uuid.
            *
            * @return the admin user uuid
            */
            public String getAdminUserUuid()
            {
                        return adminUserUuid;
            }
           
            /**
            * Sets the admin user uuid.
            *
            * @param adminUserUuid
            *            the new admin user uuid
            */
            public void setAdminUserUuid(String adminUserUuid)
            {
                        this.adminUserUuid = adminUserUuid;
            }
           
            @Override
            public String toString()
            {
                        StringBuilder builder = new StringBuilder();
                        builder.append("Account [id=");
                        builder.append(id);
                        builder.append(", accId=");
                        builder.append(accId);
                        builder.append(", accountName=");
                        builder.append(accountName);
                        builder.append(", companyName=");
                        builder.append(companyName);
                        builder.append(", companyTelephone=");
                        builder.append(companyTelephone);
                        builder.append(", companyWeb=");
                        builder.append(companyWeb);
                        builder.append(", type=");
                        builder.append(type);
                        builder.append(", adminUsername=");
                        builder.append(adminUsername);
                        builder.append(", adminPassword=");
                        builder.append(adminPassword);
                        builder.append(", adminPasswordC=");
                        builder.append(adminPasswordC);
                        builder.append(", adminFirstName=");
                        builder.append(adminFirstName);
                        builder.append(", adminLastName=");
                        builder.append(adminLastName);
                        builder.append(", emailAddress=");
                        builder.append(emailAddress);
                        builder.append(", uuid=");
                        builder.append(uuid);
                        builder.append(", adminUserUuid=");
                        builder.append(adminUserUuid);
                        builder.append(", isActive=");
                        builder.append(isActive);
                        builder.append(", approveStatus=");
                        builder.append(approveStatus);
                        builder.append(", tagIds=");
                        builder.append(Arrays.toString(tagIds));
                        builder.append(", accountTag=");
                        builder.append(accountTag);
                        builder.append(", tagCreatedBy=");
                        builder.append(tagCreatedBy);
                        builder.append(", enterprise=");
                        builder.append(enterprise);
                        builder.append("]");
                        return builder.toString();
            }
           
            /**
            * Gets the as url params.
            *
            * @return the as url params
            */
            @JsonIgnore
            public String getAsUrlParams()
            {
                        StringBuilder stringBuilder = new StringBuilder(URL_PARAMS_DEFAULT_LENGTH);
                       
                        stringBuilder.append("accountName=").append(accountName);
                        stringBuilder.append("&companyName=").append(companyName);
                        stringBuilder.append("&companyTelephone=").append(companyTelephone);
                        stringBuilder.append("&companyWeb=").append(companyWeb);
                        stringBuilder.append("&type=").append(type);
                        stringBuilder.append("&adminUsername=").append(adminUsername);
                        stringBuilder.append("&adminFirstName=").append(adminFirstName);
                        stringBuilder.append("&adminLastName=").append(adminLastName);
                        stringBuilder.append("&emailAddress=").append(emailAddress);
                        stringBuilder.append("&uuid=").append(uuid);
                        stringBuilder.append("&adminUserUuid=").append(adminUserUuid);
                       
                        return stringBuilder.toString();
            }
}




/*
* identity-json - AccountJsonSerializer.java, Sep 22, 2015 12:41:03 PM
*
 * Copyright 2015 Trimble Ltd, Inc. All rights reserved.
* Trimble proprietary/confidential. Use is subject to license terms.
*/
package com.trimble.identity.json.serializer;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

import com.trimble.identity.json.Account;
import com.trimble.identity.json.annotate.ResponseJsonIgnore;

/**
* TODO Description go here.
*
 * @author <a href="mailto:Rajakrishna_Reddy@Trimble.com">Rajakrishna V.
*         Reddy</a>
* @version 1.0
*                  
 */
public class AccountJsonSerializer extends JsonSerializer<Account>
{
      
       /** The accepted methods. */
       private final List<Method> acceptedMethods = new LinkedList<Method>();
      
       /** The rejected methods. */
       private final List<Method> rejectedMethods = new LinkedList<Method>();
      
       /**
       * Instantiates a new account json serializer.
       */
       public AccountJsonSerializer()
       {
              for (Method m : printGettersSetters(Account.class))
              {
                     final Annotation[] annotations = m.getDeclaredAnnotations();
                     boolean isAnnotated = false;
                     for (Annotation annotation : annotations)
                     {
                           if (annotation.annotationType().equals(ResponseJsonIgnore.class)
                                         || annotation.annotationType().equals(JsonIgnore.class))
                           {
                                  isAnnotated = true;
                           }
                     }
                     if (isAnnotated)
                     {
                           rejectedMethods.add(m);
                     }
                     else
                     {
                           acceptedMethods.add(m);
                     }
              }
       }
      
       /*
       * (non-Javadoc)
       *
        * @see org.codehaus.jackson.map.JsonSerializer#serialize(java.lang.Object,
       * org.codehaus.jackson.JsonGenerator,
       * org.codehaus.jackson.map.SerializerProvider)
       */
       @Override
       public void serialize(Account account, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException
       {
              jgen.writeStartObject();
              for (Method method : acceptedMethods)
              {
                     try
                     {
                           if (String.class.isAssignableFrom(method.getReturnType()))
                           {
                                  jgen.writeStringField(getFieldNameFromGetMethodName(method.getName()), (String) method.invoke(account, Collections.emptyList().toArray()));
                           }
                           else if (method.getReturnType().toString().equalsIgnoreCase("int") || Integer.class.isAssignableFrom(method.getReturnType()))
                           {
                                  jgen.writeNumberField(getFieldNameFromGetMethodName(method.getName()), (Integer) method.invoke(account, Collections.emptyList().toArray()));
                           }
                           else if (method.getReturnType().toString().equalsIgnoreCase("float") || Float.class.isAssignableFrom(method.getReturnType()))
                           {
                                  jgen.writeNumberField(getFieldNameFromGetMethodName(method.getName()), (Float) method.invoke(account, Collections.emptyList().toArray()));
                           }
                           else if (method.getReturnType().toString().equalsIgnoreCase("boolean") || Boolean.class.isAssignableFrom(method.getReturnType()))
                           {
                                  jgen.writeBooleanField(getFieldNameFromGetMethodName(method.getName()), (Boolean) method.invoke(account, Collections.emptyList().toArray()));
                           }
                     }
                     catch (Exception e)
                     {
                           e.printStackTrace();
                     }
              }
              jgen.writeEndObject();
       }
      
       /**
       * Prints the getters setters.
       *
       * @param <T>
       *            the generic type
       * @param aClass
       *            the a class
       * @return the list
       */
       public static <T> List<Method> printGettersSetters(Class<T> aClass)
       {
              final Method[] methods = aClass.getDeclaredMethods();
              final List<Method> getterMethods = new LinkedList<Method>();
              for (Method method : methods)
              {
                     if (isGetter(method))
                     {
                           getterMethods.add(method);
                     }
              }
              return getterMethods;
       }
      
       /**
       * Checks if is getter.
       *
       * @param method
       *            the method
       * @return true, if is getter
       */
       public static boolean isGetter(Method method)
       {
              if (!(method.getName().startsWith("get") || method.getName().startsWith("is")))
                     return false;
              if (method.getParameterTypes().length != 0)
                     return false;
              if (void.class.equals(method.getReturnType()))
                     return false;
              return true;
       }
      
       /**
       * Checks if is setter.
       *
       * @param method
       *            the method
       * @return true, if is setter
       */
       public static boolean isSetter(Method method)
       {
              if (!method.getName().startsWith("set"))
                     return false;
              if (method.getParameterTypes().length != 1)
                     return false;
              return true;
       }
      
       public static String getFieldNameFromGetMethodName(String method)
       {
              if (method.startsWith("get"))
              {
                     return String.valueOf(method.charAt(3)).toLowerCase() + method.substring(4);
              }
              else
              {
                     return String.valueOf(method.charAt(2)).toLowerCase() + method.substring(3);
              }
       }
      
       /**
       * Entry point to the entire application, contains the list of args to pass
       * the user defined values.
       *
       * @param args
       *            the arguments
       * @throws InvocationTargetException
       * @throws IllegalArgumentException
       * @throws IllegalAccessException
       */
       public static void main(String... argsthrows IllegalAccessException, IllegalArgumentException, InvocationTargetException
       {
              AccountJsonSerializer serializer = new AccountJsonSerializer();
              System.out.println("AM: " + serializer.acceptedMethods);
              System.out.println("RM: " + serializer.rejectedMethods);
             
              Account account = new Account();
              account.setId(21);
              account.setEnterprise(true);
             
              for (Method string : serializer.acceptedMethods)
              {
                     if (string.getReturnType().isArray())
                     {
                     }
              }
              System.out.println(serializer.acceptedMethods.get(0).invoke(account, Collections.emptyList().toArray()));
              System.out.println(Integer.class.isAssignableFrom(serializer.acceptedMethods.get(0).getReturnType()));
              System.out.println(serializer.acceptedMethods.get(0).getReturnType().isAssignableFrom(String.class));
              System.out.println(serializer.acceptedMethods.get(0).getReturnType().isAssignableFrom(Float.class));
              /*
              * for (Method string : serializer.acceptedMethods) {
              * System.out.println("id: "
              * +getFieldNameFromGetMethodName(string.getName())); } for (Method
              * string : serializer.rejectedMethods) { System.out.println("id: "
              * +getFieldNameFromGetMethodName(string.getName())); }
              */
       }
}



package com.varra.identity.json.annotate;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.codehaus.jackson.annotate.JacksonAnnotation;

/**
* Marker annotation that indicates that the annotated method or field is to be
* ignored by introspection-based serialization functionality in the response.
 * That is, it should not be consider a "getter", "setter" or "creator".
* <p>
* For example, a "getter" method that would otherwise denote a property (like,
* say, "getValue" to suggest property "value") to serialize, would be ignored
* and no such property would be output unless another annotation defines
* alternative method to use.
* <p>
* This annotation works purely on method-by-method (or field-by-field) basis;
* annotation on one method or field does not imply ignoring other methods or
* fields. Specifically, marking a "setter" candidate does not change handling
* of matching "getter" method (or vice versa).
* <p>
* Annotation is usually used just a like a marker annotation, that is, without
* explicitly defining 'value' argument (which defaults to <code>true</code>):
* but argument can be explicitly defined. This can be done to override an
* existing JsonIgnore by explictly defining one with 'false' argument.
* <p>
* Annotation is similar to {@link javax.xml.bind.annotation.XmlTransient}
*
 * @author Rajakrishna V. Reddy
* @version 1.0
*/
@Target({ ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface ResponseJsonIgnore
{
           
            /**
            * Optional argument that defines whether this annotation is active or not.
            * The only use for value 'false' if for overriding purposes (which is not
            * needed often); most likely it is needed for use with "mix-in annotations"
            * (aka "annotation overrides"). For most cases, however, default value of
            * "true" is just fine and should be omitted.
            *
            * @return true, if successful
            */
            boolean value() default true;
}



Monday, August 24, 2015

How to increase permgen space in tomcat

Tomcat is managed by this script file catalina.bat, dive inside the script, you will find out that catalina.bat always find and run the setenv.bat file to set the environment variables.

 

{$tomcat-folder}\bin\catalina.bat

 

//...

rem Get standard environment variables

if not exist "%CATALINA_BASE%\bin\setenv.bat" goto checkSetenvHome

call "%CATALINA_BASE%\bin\setenv.bat"

goto setenvDone

:checkSetenvHome

if exist "%CATALINA_HOME%\bin\setenv.bat" call "%CATALINA_HOME%\bin\setenv.bat"

:setenvDone

//...

 

 

2.1 To set the environment variable on Windows, create a setenv.bat manually, and put it into the ${tomcat-folder}\bin folder.

 

${tomcat-folder}\bin\setenv.bat

set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

P.S No double quotes, set JAVA_OPTS={value}.

 

2.2 Restart Tomcat, it will call the setenv.bat file to set the environment variable automatically.

 

{$tomcat-folder}\bin\catalina.bat restart

 



Thanks & Regards,

Rajakrishna Reddy,

+91 95000 88012

 

 

Thursday, August 20, 2015

WSO2 Governance Registry - Monitor database operations using log4jdbc

WSO2 Governance Registry - Monitor database operations using log4jdbc

LOG4JDBC is a Java based database driver that can be used to log SQL and/or JDBC calls. So here I am going to show how to monitor JDBC operations on Governance Registry using log4jdbc.

Here I believe you have already configured Governance Registry instance with MySQL. If not, please follow the instruction available in the Governance Registry documentation.

1). Download the log4jdbc driver

 You can download log4jdbc driver from below location: https://code.google.com/p/log4jdbc/

2). Add log4jdbc driver

 Copy log4jdbc driver into CARBON_HOME/repository/components/lib directory. 

3). Configure log4j.properties file.

Navigate to log4j.properties file located in CARBON_HOME/repository/conf/ directory and add below entry in to log4j.properties file.

# Log all JDBC calls except for ResultSet calls
log4j.logger.jdbc.audit=INFO,jdbc
log4j.additivity.jdbc.audit=false

# Log only JDBC calls to ResultSet objects
log4j.logger.jdbc.resultset=INFO,jdbc
log4j.additivity.jdbc.resultset=false

# Log only the SQL that is executed.
log4j.logger.jdbc.sqlonly=DEBUG,sql
log4j.additivity.jdbc.sqlonly=false

# Log timing information about the SQL that is executed.
log4j.logger.jdbc.sqltiming=DEBUG,sqltiming
log4j.additivity.jdbc.sqltiming=false

# Log connection open/close events and connection number dump
log4j.logger.jdbc.connection=FATAL,connection
log4j.additivity.jdbc.connection=false

# the appender used for the JDBC API layer call logging above, sql only
log4j.appender.sql=org.apache.log4j.FileAppender
log4j.appender.sql.File=${carbon.home}/repository/logs/sql.log
log4j.appender.sql.Append=false
log4j.appender.sql.layout=org.apache.log4j.PatternLayout
log4j.appender.sql.layout.ConversionPattern=-----> %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n

# the appender used for the JDBC API layer call logging above, sql timing
log4j.appender.sqltiming=org.apache.log4j.FileAppender
log4j.appender.sqltiming.File=${carbon.home}/repository/logs/sqltiming.log
log4j.appender.sqltiming.Append=false
log4j.appender.sqltiming.layout=org.apache.log4j.PatternLayout
log4j.appender.sqltiming.layout.ConversionPattern=-----> %d{yyyy-MM-dd HH:mm:ss.SSS} %m%n%n

# the appender used for the JDBC API layer call logging above
log4j.appender.jdbc=org.apache.log4j.FileAppender
log4j.appender.jdbc.File=${carbon.home}/repository/logs/jdbc.log
log4j.appender.jdbc.Append=false
log4j.appender.jdbc.layout=org.apache.log4j.PatternLayout
log4j.appender.jdbc.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n

# the appender used for the JDBC Connection open and close events
log4j.appender.connection=org.apache.log4j.FileAppender
log4j.appender.connection.File=${carbon.home}/repository/logs/connection.log
log4j.appender.connection.Append=false
log4j.appender.connection.layout=org.apache.log4j.PatternLayout
log4j.appender.connection.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSS} %m%n



4). Update the master-datasources.xml file

Update the master-datasources.xml file located in CARBON_HOME/repository/conf/datasources directory. There each datasource URL and Drivers as below

<url>jdbc:log4jdbc:mysql://localhost:3306/amdb?autoReconnect=true</url>
<driverClassName>net.sf.log4jdbc.DriverSpy</driverClassName>

5). Enjoy

Some database drvers may not support by default(ex :db2), there you can pass database driver name as VM argument

-Dlog4jdbc.drivers=com.ibm.db2.jcc.DB2Driver

Restart the server and enjoy your work with log4jdbc. Log files are created under CARBON_HOME/repository/logs/ directory. So using sqltiming.log file you can monitor execution time of each query.

 

Thursday, July 9, 2015

How to loop through multiple CSV files in JMeter


Here is a simple way to play with multiple CSV files in JMeter! Just copy and save the given code as a JMX file and load it into JMeter, you would probable be having a view something like shown here! And Enjoy!

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="2.6" jmeter="2.11 r1554548">
  <hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="APICloudBenchMarking-PreRequisites" enabled="true">
      <stringProp name="TestPlan.comments"></stringProp>
      <boolProp name="TestPlan.functional_mode">false</boolProp>
      <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
      <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments">
          <elementProp name="requestUrlForAccountProvisionAPI" elementType="Argument">
            <stringProp name="Argument.name">requestUrlForAccountProvisionAPI</stringProp>
            <stringProp name="Argument.value">api-dev1.trimble.com/t/trimble.com/testaccountIdentityService/1.0/account</stringProp>
            <stringProp name="Argument.metadata">=</stringProp>
          </elementProp>
          <elementProp name="requestUrlForUserProvisionAPI" elementType="Argument">
            <stringProp name="Argument.name">requestUrlForUserProvisionAPI</stringProp>
            <stringProp name="Argument.value">api-dev1.trimble.com/t/trimble.com/testuserIdentityService/1.0/user</stringProp>
            <stringProp name="Argument.metadata">=</stringProp>
          </elementProp>
          <elementProp name="Testdata_LoopCount" elementType="Argument">
            <stringProp name="Argument.name">Testdata_LoopCount</stringProp>
            <stringProp name="Argument.value">2</stringProp>
            <stringProp name="Argument.metadata">=</stringProp>
          </elementProp>
          <elementProp name="AddAccount_Datasource" elementType="Argument">
            <stringProp name="Argument.name">AddAccount_Datasource</stringProp>
            <stringProp name="Argument.value">Account_Test_Data.csv</stringProp>
            <stringProp name="Argument.metadata">=</stringProp>
          </elementProp>
          <elementProp name="AddUser_Datasource" elementType="Argument">
            <stringProp name="Argument.name">AddUser_Datasource</stringProp>
            <stringProp name="Argument.value">User_Test_Data.csv</stringProp>
            <stringProp name="Argument.metadata">=</stringProp>
          </elementProp>
        </collectionProp>
      </elementProp>
      <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="LoadApis" enabled="false">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <intProp name="LoopController.loops">-1</intProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <longProp name="ThreadGroup.start_time">1414742816000</longProp>
        <longProp name="ThreadGroup.end_time">1414742816000</longProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration">900</stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </ThreadGroup>
      <hashTree>
        <BeanShellPreProcessor guiclass="TestBeanGUI" testclass="BeanShellPreProcessor" testname="UserCountProcessor" enabled="true">
          <stringProp name="filename"></stringProp>
          <stringProp name="parameters"></stringProp>
          <boolProp name="resetInterpreter">false</boolProp>
          <stringProp name="script">import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
 
FileReader fileReader = new FileReader(new File(&quot;C:\\Users\\rareddy\\Desktop\\shared-services\\jmx-test\\TID Perf Test\\krishna\\APICloud\\UserDetails.csv&quot;));
LineNumberReader lineReader = new LineNumberReader(fileReader);
int linenumber = 0;
while (lineReader.readLine() != null){
   linenumber++;
}
//linenumber--; // do not include header row
props.put(&quot;LineCount&quot;, Integer.toString(linenumber));
lineReader.close();</stringProp>
        </BeanShellPreProcessor>
        <hashTree/>
        <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="Api Data Config" enabled="true">
          <stringProp name="delimiter">,</stringProp>
          <stringProp name="fileEncoding"></stringProp>
          <stringProp name="filename">ApiDetails.csv</stringProp>
          <boolProp name="quotedData">false</boolProp>
          <boolProp name="recycle">false</boolProp>
          <stringProp name="shareMode">shareMode.all</stringProp>
          <boolProp name="stopThread">true</boolProp>
          <stringProp name="variableNames">ApiName</stringProp>
        </CSVDataSet>
        <hashTree/>
        <LoopController guiclass="LoopControlPanel" testclass="LoopController" testname="User Count Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">true</boolProp>
          <stringProp name="LoopController.loops">${__P(LineCount)}</stringProp>
        </LoopController>
        <hashTree>
          <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="User Data Config" enabled="true">
            <stringProp name="delimiter">,</stringProp>
            <stringProp name="fileEncoding"></stringProp>
            <stringProp name="filename">UserDetails.csv</stringProp>
            <boolProp name="quotedData">false</boolProp>
            <boolProp name="recycle">true</boolProp>
            <stringProp name="shareMode">shareMode.all</stringProp>
            <boolProp name="stopThread">false</boolProp>
            <stringProp name="variableNames">userName</stringProp>
          </CSVDataSet>
          <hashTree/>
          <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="AddApi" enabled="true">
            <boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
            <elementProp name="HTTPsampler.Arguments" elementType="Arguments">
              <collectionProp name="Arguments.arguments">
                <elementProp name="" elementType="HTTPArgument">
                  <boolProp name="HTTPArgument.always_encode">false</boolProp>
                  <stringProp name="Argument.value">{&quot;userName&quot;:&quot;${ApiName}&quot;,&quot;firstName&quot;:&quot;${userName}&quot;,&quot;userCount&quot;:&quot;${__P(LineCount)}&quot;}</stringProp>
                  <stringProp name="Argument.metadata">=</stringProp>
                </elementProp>
              </collectionProp>
            </elementProp>
            <stringProp name="HTTPSampler.domain">api-pp.trimblepaas.com</stringProp>
            <stringProp name="HTTPSampler.port"></stringProp>
            <stringProp name="HTTPSampler.connect_timeout"></stringProp>
            <stringProp name="HTTPSampler.response_timeout"></stringProp>
            <stringProp name="HTTPSampler.protocol">https</stringProp>
            <stringProp name="HTTPSampler.contentEncoding"></stringProp>
            <stringProp name="HTTPSampler.path">publisher</stringProp>
            <stringProp name="HTTPSampler.method">POST</stringProp>
            <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
            <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
            <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
            <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
            <stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
            <boolProp name="HTTPSampler.monitor">false</boolProp>
            <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
          </HTTPSamplerProxy>
          <hashTree>
            <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="false">
              <boolProp name="ResultCollector.error_logging">false</boolProp>
              <objProp>
                <name>saveConfig</name>
                <value class="SampleSaveConfiguration">
                  <time>true</time>
                  <latency>true</latency>
                  <timestamp>true</timestamp>
                  <success>true</success>
                  <label>true</label>
                  <code>true</code>
                  <message>true</message>
                  <threadName>true</threadName>
                  <dataType>true</dataType>
                  <encoding>false</encoding>
                  <assertions>true</assertions>
                  <subresults>true</subresults>
                  <responseData>false</responseData>
                  <samplerData>false</samplerData>
                  <xml>false</xml>
                  <fieldNames>false</fieldNames>
                  <responseHeaders>false</responseHeaders>
                  <requestHeaders>false</requestHeaders>
                  <responseDataOnError>false</responseDataOnError>
                  <saveAssertionResultsFailureMessage>false</saveAssertionResultsFailureMessage>
                  <assertionsResultsToSave>0</assertionsResultsToSave>
                  <bytes>true</bytes>
                </value>
              </objProp>
              <stringProp name="filename"></stringProp>
            </ResultCollector>
            <hashTree/>
          </hashTree>
        </hashTree>
      </hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="LoadAppplications" enabled="false">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <intProp name="LoopController.loops">-1</intProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <longProp name="ThreadGroup.start_time">1414742816000</longProp>
        <longProp name="ThreadGroup.end_time">1414742816000</longProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration">900</stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </ThreadGroup>
      <hashTree>
        <BeanShellPreProcessor guiclass="TestBeanGUI" testclass="BeanShellPreProcessor" testname="UserCountProcessor" enabled="true">
          <stringProp name="filename"></stringProp>
          <stringProp name="parameters"></stringProp>
          <boolProp name="resetInterpreter">false</boolProp>
          <stringProp name="script">import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
 
FileReader fileReader = new FileReader(new File(&quot;C:\\Users\\rareddy\\Desktop\\shared-services\\jmx-test\\TID Perf Test\\krishna\\APICloud\\UserDetails.csv&quot;));
LineNumberReader lineReader = new LineNumberReader(fileReader);
int linenumber = 0;
while (lineReader.readLine() != null){
   linenumber++;
}
//linenumber--; // do not include header row
props.put(&quot;LineCount&quot;, Integer.toString(linenumber));
lineReader.close();</stringProp>
        </BeanShellPreProcessor>
        <hashTree/>
        <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="Appplication Data Config" enabled="true">
          <stringProp name="delimiter">,</stringProp>
          <stringProp name="fileEncoding"></stringProp>
          <stringProp name="filename">ApplicationDetails.csv</stringProp>
          <boolProp name="quotedData">false</boolProp>
          <boolProp name="recycle">false</boolProp>
          <stringProp name="shareMode">shareMode.all</stringProp>
          <boolProp name="stopThread">true</boolProp>
          <stringProp name="variableNames">ApiName</stringProp>
        </CSVDataSet>
        <hashTree/>
        <LoopController guiclass="LoopControlPanel" testclass="LoopController" testname="User Count Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">true</boolProp>
          <stringProp name="LoopController.loops">${__P(LineCount)}</stringProp>
        </LoopController>
        <hashTree>
          <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="User Data Config" enabled="true">
            <stringProp name="delimiter">,</stringProp>
            <stringProp name="fileEncoding"></stringProp>
            <stringProp name="filename">UserDetails.csv</stringProp>
            <boolProp name="quotedData">false</boolProp>
            <boolProp name="recycle">true</boolProp>
            <stringProp name="shareMode">shareMode.all</stringProp>
            <boolProp name="stopThread">false</boolProp>
            <stringProp name="variableNames">userName</stringProp>
          </CSVDataSet>
          <hashTree/>
          <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="AddApplication" enabled="true">
            <boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
            <elementProp name="HTTPsampler.Arguments" elementType="Arguments">
              <collectionProp name="Arguments.arguments">
                <elementProp name="" elementType="HTTPArgument">
                  <boolProp name="HTTPArgument.always_encode">false</boolProp>
                  <stringProp name="Argument.value">{&quot;userName&quot;:&quot;${ApiName}&quot;,&quot;firstName&quot;:&quot;${userName}&quot;,&quot;userCount&quot;:&quot;${__P(LineCount)}&quot;}</stringProp>
                  <stringProp name="Argument.metadata">=</stringProp>
                </elementProp>
              </collectionProp>
            </elementProp>
            <stringProp name="HTTPSampler.domain">api-pp.trimblepaas.com</stringProp>
            <stringProp name="HTTPSampler.port"></stringProp>
            <stringProp name="HTTPSampler.connect_timeout"></stringProp>
            <stringProp name="HTTPSampler.response_timeout"></stringProp>
            <stringProp name="HTTPSampler.protocol">https</stringProp>
            <stringProp name="HTTPSampler.contentEncoding"></stringProp>
            <stringProp name="HTTPSampler.path">publisher</stringProp>
            <stringProp name="HTTPSampler.method">POST</stringProp>
            <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
            <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
            <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
            <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
            <stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
            <boolProp name="HTTPSampler.monitor">false</boolProp>
            <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
          </HTTPSamplerProxy>
          <hashTree>
            <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="false">
              <boolProp name="ResultCollector.error_logging">false</boolProp>
              <objProp>
                <name>saveConfig</name>
                <value class="SampleSaveConfiguration">
                  <time>true</time>
                  <latency>true</latency>
                  <timestamp>true</timestamp>
                  <success>true</success>
                  <label>true</label>
                  <code>true</code>
                  <message>true</message>
                  <threadName>true</threadName>
                  <dataType>true</dataType>
                  <encoding>false</encoding>
                  <assertions>true</assertions>
                  <subresults>true</subresults>
                  <responseData>false</responseData>
                  <samplerData>false</samplerData>
                  <xml>false</xml>
                  <fieldNames>false</fieldNames>
                  <responseHeaders>false</responseHeaders>
                  <requestHeaders>false</requestHeaders>
                  <responseDataOnError>false</responseDataOnError>
                  <saveAssertionResultsFailureMessage>false</saveAssertionResultsFailureMessage>
                  <assertionsResultsToSave>0</assertionsResultsToSave>
                  <bytes>true</bytes>
                </value>
              </objProp>
              <stringProp name="filename"></stringProp>
            </ResultCollector>
            <hashTree/>
          </hashTree>
        </hashTree>
      </hashTree>
      <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Subscription" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">false</boolProp>
          <intProp name="LoopController.loops">-1</intProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <longProp name="ThreadGroup.start_time">1414742816000</longProp>
        <longProp name="ThreadGroup.end_time">1414742816000</longProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration">900</stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
      </ThreadGroup>
      <hashTree>
        <BeanShellPreProcessor guiclass="TestBeanGUI" testclass="BeanShellPreProcessor" testname="UserCountProcessor" enabled="true">
          <stringProp name="filename"></stringProp>
          <stringProp name="parameters"></stringProp>
          <boolProp name="resetInterpreter">false</boolProp>
          <stringProp name="script">import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
 
FileReader fileReader = new FileReader(new File(&quot;C:\\Users\\rareddy\\Desktop\\shared-services\\jmx-test\\TID Perf Test\\krishna\\APICloud\\UserDetails.csv&quot;));
LineNumberReader lineReader = new LineNumberReader(fileReader);
int linenumber = 0;
while (lineReader.readLine() != null){
   linenumber++;
}
//linenumber--; // do not include header row
props.put(&quot;UserCount&quot;, Integer.toString(linenumber));
lineReader.close();</stringProp>
        </BeanShellPreProcessor>
        <hashTree/>
        <BeanShellPreProcessor guiclass="TestBeanGUI" testclass="BeanShellPreProcessor" testname="ApiCountProcessor" enabled="true">
          <stringProp name="filename"></stringProp>
          <stringProp name="parameters"></stringProp>
          <boolProp name="resetInterpreter">false</boolProp>
          <stringProp name="script">import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
 
FileReader fileReader = new FileReader(new File(&quot;C:\\Users\\rareddy\\Desktop\\shared-services\\jmx-test\\TID Perf Test\\krishna\\APICloud\\ApiDetails.csv&quot;));
LineNumberReader lineReader = new LineNumberReader(fileReader);
int linenumber = 0;
while (lineReader.readLine() != null){
   linenumber++;
}
//linenumber--; // do not include header row
props.put(&quot;ApiCount&quot;, Integer.toString(linenumber));
lineReader.close();</stringProp>
        </BeanShellPreProcessor>
        <hashTree/>
        <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="Appplication Data Config" enabled="true">
          <stringProp name="delimiter">,</stringProp>
          <stringProp name="fileEncoding"></stringProp>
          <stringProp name="filename">ApplicationDetails.csv</stringProp>
          <boolProp name="quotedData">false</boolProp>
          <boolProp name="recycle">false</boolProp>
          <stringProp name="shareMode">shareMode.all</stringProp>
          <boolProp name="stopThread">true</boolProp>
          <stringProp name="variableNames">ApiName</stringProp>
        </CSVDataSet>
        <hashTree/>
        <LoopController guiclass="LoopControlPanel" testclass="LoopController" testname="Api Count Controller" enabled="true">
          <boolProp name="LoopController.continue_forever">true</boolProp>
          <stringProp name="LoopController.loops">${__P(ApiCount)}</stringProp>
        </LoopController>
        <hashTree>
          <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="Api Data Config" enabled="true">
            <stringProp name="delimiter">,</stringProp>
            <stringProp name="fileEncoding"></stringProp>
            <stringProp name="filename">ApiDetails.csv</stringProp>
            <boolProp name="quotedData">false</boolProp>
            <boolProp name="recycle">true</boolProp>
            <stringProp name="shareMode">shareMode.all</stringProp>
            <boolProp name="stopThread">false</boolProp>
            <stringProp name="variableNames">ApiName</stringProp>
          </CSVDataSet>
          <hashTree/>
          <LoopController guiclass="LoopControlPanel" testclass="LoopController" testname="User Count Controller" enabled="true">
            <boolProp name="LoopController.continue_forever">true</boolProp>
            <stringProp name="LoopController.loops">${__P(UserCount)}</stringProp>
          </LoopController>
          <hashTree>
            <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="User Data Config" enabled="true">
              <stringProp name="delimiter">,</stringProp>
              <stringProp name="fileEncoding"></stringProp>
              <stringProp name="filename">UserDetails.csv</stringProp>
              <boolProp name="quotedData">false</boolProp>
              <boolProp name="recycle">true</boolProp>
              <stringProp name="shareMode">shareMode.all</stringProp>
              <boolProp name="stopThread">false</boolProp>
              <stringProp name="variableNames">userName</stringProp>
            </CSVDataSet>
            <hashTree/>
            <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="AddApplication" enabled="true">
              <boolProp name="HTTPSampler.postBodyRaw">true</boolProp>
              <elementProp name="HTTPsampler.Arguments" elementType="Arguments">
                <collectionProp name="Arguments.arguments">
                  <elementProp name="" elementType="HTTPArgument">
                    <boolProp name="HTTPArgument.always_encode">false</boolProp>
                    <stringProp name="Argument.value">{&quot;userName&quot;:&quot;${ApiName}&quot;,&quot;firstName&quot;:&quot;${userName}&quot;,&quot;userCount&quot;:&quot;${__P(LineCount)}&quot;}</stringProp>
                    <stringProp name="Argument.metadata">=</stringProp>
                  </elementProp>
                </collectionProp>
              </elementProp>
              <stringProp name="HTTPSampler.domain">api-pp.trimblepaas.com</stringProp>
              <stringProp name="HTTPSampler.port"></stringProp>
              <stringProp name="HTTPSampler.connect_timeout"></stringProp>
              <stringProp name="HTTPSampler.response_timeout"></stringProp>
              <stringProp name="HTTPSampler.protocol">https</stringProp>
              <stringProp name="HTTPSampler.contentEncoding"></stringProp>
              <stringProp name="HTTPSampler.path">publisher</stringProp>
              <stringProp name="HTTPSampler.method">POST</stringProp>
              <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
              <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
              <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
              <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
              <stringProp name="HTTPSampler.implementation">HttpClient4</stringProp>
              <boolProp name="HTTPSampler.monitor">false</boolProp>
              <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
            </HTTPSamplerProxy>
            <hashTree>
              <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="false">
                <boolProp name="ResultCollector.error_logging">false</boolProp>
                <objProp>
                  <name>saveConfig</name>
                  <value class="SampleSaveConfiguration">
                    <time>true</time>
                    <latency>true</latency>
                    <timestamp>true</timestamp>
                    <success>true</success>
                    <label>true</label>
                    <code>true</code>
                    <message>true</message>
                    <threadName>true</threadName>
                    <dataType>true</dataType>
                    <encoding>false</encoding>
                    <assertions>true</assertions>
                    <subresults>true</subresults>
                    <responseData>false</responseData>
                    <samplerData>false</samplerData>
                    <xml>false</xml>
                    <fieldNames>false</fieldNames>
                    <responseHeaders>false</responseHeaders>
                    <requestHeaders>false</requestHeaders>
                    <responseDataOnError>false</responseDataOnError>
                    <saveAssertionResultsFailureMessage>false</saveAssertionResultsFailureMessage>
                    <assertionsResultsToSave>0</assertionsResultsToSave>
                    <bytes>true</bytes>
                  </value>
                </objProp>
                <stringProp name="filename"></stringProp>
              </ResultCollector>
              <hashTree/>
            </hashTree>
          </hashTree>
          <CSVDataSet guiclass="TestBeanGUI" testclass="CSVDataSet" testname="User Data Config" enabled="true">
            <stringProp name="delimiter">,</stringProp>
            <stringProp name="fileEncoding"></stringProp>
            <stringProp name="filename">UserDetails.csv</stringProp>
            <boolProp name="quotedData">false</boolProp>
            <boolProp name="recycle">true</boolProp>
            <stringProp name="shareMode">shareMode.all</stringProp>
            <boolProp name="stopThread">false</boolProp>
            <stringProp name="variableNames">userName</stringProp>
          </CSVDataSet>
          <hashTree/>
        </hashTree>
      </hashTree>
      <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
          <name>saveConfig</name>
          <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>false</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>false</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
          </value>
        </objProp>
        <stringProp name="filename">1436438845555</stringProp>
      </ResultCollector>
      <hashTree/>
      <ResultCollector guiclass="TableVisualizer" testclass="ResultCollector" testname="View Results in Table" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
          <name>saveConfig</name>
          <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>false</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>false</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
          </value>
        </objProp>
        <stringProp name="filename"></stringProp>
      </ResultCollector>
      <hashTree/>
    </hashTree>
  </hashTree>
</jmeterTestPlan>





Have a nice time!

Thursday, June 18, 2015

How to push build artifacts to remote repository using Maven

Hello! After a bit long time, I am writing a post in this "Gyan of Java" blog. Today, we will look into few concepts of Apache Maven building tool. Have you ever come across a situation where you need to push build artifacts to a remote repository? Have you ever come across a situation where you need to push third party artifacts to a remote repository? Let's look into these now.


To answer first query, need to add a <distributionManagement> tag entries in the pom.xml of the application.

Step: 1
 
<!-- remote repository server info where artifacts would be pushed -->
 <distributionManagement>
  <repository>
   <id>remoteRepo</id>
   <name>Internal Nexus Repository</name>
   <url>http://<remote host name>:<port name>/<remote repository path>/</url>
  </repository>
</distributionManagement>


Also, need to below add entries in the settings.xml file located in M2_HOME directory.

Step: 2
   <servers>
<server>
<id>remoteRepo</id>
<username><username></username>
<password><password></password>
</server>

  </servers>

 

 

After doing these changes, build your app with following command:

mvn clean deploy

 

Regarding the later question, pushing third party artifacts whose pom.xml is not available, below is the code snippet.

 

Step: 3

mvn deploy:deploy-file -DgroupId=com.company.app -DartifactId=appName -Dversion=1.0 -Dfile=<path-to-file>/appName.jar -Dpackaging=jar -DrepositoryId=remoteRepo -Durl=http://<remote host>:<port no>/<remote repository path> -DgeneratePom=true

 

but before executing Step :3 command, please make sure to add entries in settings.xml file as mentioned in Step: 2

 

 

Wednesday, June 10, 2015

How to pass environment variables to tomact

Just change the below file in order to pass environment variables to tomcat.

TOMCAT_HOME/bin/catalina.sh  

 

And keep the below line:

JAVA_OPTS="$JAVA_OPTS -Dkey=$value"

Monday, April 13, 2015

How to append url parameters in Wso2 API Manager

Appending url parameters in Wso2 API Manager using custom sequences:

 

<sequence xmlns="http://ws.apache.org/ns/synapse" name="eCommerce--Aria-add-params--In">

    <property name="REST_URL_POSTFIX" expression="fn:concat(get-property('axis2','REST_URL_POSTFIX'), '&amp;auth_key=mps8qpVB6NwjPgPGMJCNnAGKvHxNDbaX')" scope="axis2" type="STRING"/>

    <property name="REST_URL_POSTFIX" expression="fn:concat(get-property('axis2','REST_URL_POSTFIX'), '&amp;client_no=4974461')" scope="axis2" type="STRING"/>

    <log level="full">

        <property name="TRACE" value="Adding url params by Rajakrishna Reddy"/>

    </log>

</sequence>