18 July 2018

JAVA SetUp in System

JAVA ENVIRONMENT SET UP 
===========================
In System Variables

JAVA_HOME : C:\Program Files\Java\jdk1.8.0_144
JDK_HOME  : %JAVA_HOME%
JRE_HOME  : %JAVA_HOME%\jre
CLASSPATH : .;%JAVA_HOME%\lib;%JAVA_HOME%\jre\lib
PATH      : Existing-entries;%JAVA_HOME%\bin


Maven
=======
In System Variables

1. Add JAVA_HOME as mentioned above
2. MAVEN_HOME/M2_HOME : C:\Program Files\Apache\maven
3. PATH : alreadyExistingPath;%MAVEN_HOME/M2_HOME%\bin

check console: mvn -version


ANT
========
In System Variables

ANT_HOME : c:\xx\apache-ant-x.x
PATH : alreadyExistingPath;% ANT_HOME%\bin

check console: ant -v

18 October 2017

Setting up ActiveMQ with MSSQL database

Normally the messages which we have sent are stored/retrieved in/from queues via KahaDB which is an inbuilt in ActiveMQ. So in order to save/send them database we need to follow the below process.

1.Create a new database in SQL Server with name activemq
2.If you already have activeMQ, edit or change the configuration in activemq.xml as

activemq.xml
==========
<beans
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:amq="http://activemq.apache.org/schema/core"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
  http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd">

    <!-- Allows us to use system properties and fabric as variables in this configuration file -->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties">
            <bean class="org.fusesource.mq.fabric.ConfigurationProperties"/>
        </property>     
    </bean>
   
     <bean id="mssql-ds" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
      <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=activemq"/>
        <property name="username" value="username"/>
        <property name="password" value="password"/>
        <property name="poolPreparedStatements" value="true"/>
      </bean>


    <broker xmlns="http://activemq.apache.org/schema/core"
            brokerName="localhost">

        <destinationPolicy>
            <policyMap>
              <policyEntries>
                <policyEntry topic=">" producerFlowControl="true">
                  <pendingMessageLimitStrategy>
                    <constantPendingMessageLimitStrategy limit="1000"/>
                  </pendingMessageLimitStrategy>
                </policyEntry>
                <policyEntry queue=">" producerFlowControl="true" memoryLimit="1mb">
                </policyEntry>
              </policyEntries>
            </policyMap>
        </destinationPolicy>

        <managementContext>
            <managementContext createConnector="false"/>
        </managementContext>

         <persistenceAdapter>
         <!--   <kahaDB directory="${data}/kahadb"/>  -->
         <jdbcPersistenceAdapter dataDirectory="${activemq.base}/data" dataSource="#mssql-ds" />
      </persistenceAdapter>
 
        <plugins>
            <jaasAuthenticationPlugin configuration="karaf" />
        </plugins>

        <systemUsage>
            <systemUsage>
                <memoryUsage>
                    <memoryUsage limit="64 mb"/>
                </memoryUsage>
                <storeUsage>
                    <storeUsage limit="100 gb"/>
                </storeUsage>
                <tempUsage>
                    <tempUsage limit="50 gb"/>
                </tempUsage>
            </systemUsage>
        </systemUsage>
       
        <transportConnectors>
            <transportConnector name="openwire" uri="tcp://0.0.0.0:0?maximumConnections=1000"/>
        </transportConnectors>
    </broker>

</beans>


I have added an extra spring bean configuration mention and configuring Database properties in it
I have also commented the kahaDB PersistenceAdaptor and have configured our own JdbcPersistenceAdaptor.

3.Add mssql jdbc.jar and apache dbcp2 to the lib folder inside the ActiveMQ
4.Start the amq.bat file and login with the credentials.
5.Create a queue and send a message you will observe the following tables in DB
                         ACTIVEMQ_ACKS
                        ACTIVEMQ_LOCK
                        ACTIVEMQ_MSGS
ID | CONTAINER | MSGID_PROD | MSGID_SEQ | EXPIRATION | MSG | PRIORITY | XID |
+----+-------------------+-----------------------------------------------+-----------+------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------+------+
| 1 | queue://test1 | ID:omkar-laptop-86745-3612547785654-6:2:4:2 | 1 | 0 | � { )ID:omkar-laptop-86745-3612547785654-6:8 d test1 { )ID:omkar-laptop-86745-3612547785654-3:1 I|� �
hi . I|� � | 0 | NULL |

1 row in set (0.00 sec)



Sending Log4j Logger Messages to Database[SQL SERVER]

Usually we use log4j to append the logger messages to log files in server but we can send the logger messages to Database by the following process

Here I developed an application to send logger messages to Database.




SaveLLogsToDB.java
====================

package com.omu;
package  com.omu;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.sql.*;
import java.io.*;
import java.util.*;

    public class SaveLLogsToDB {
       /* Get actual class name to be printed on */
       static Logger log = Logger.getLogger(SaveLLogsToDB.class.getName());
      
       public static void main(String[] args){
           String log4jConfPath = "src/resources/log4j.properties";
           PropertyConfigurator.configure(log4jConfPath);
          log.debug("Debug");
          log.info("Info");
          log.debug("amicorp");
          System.out.println("finish");
          System.out.println("Logs are saved to Database. Please open your Database and check the results");
          System.out.println("The logs are saved according to your system timings");
       }
    }















Log4j.properties
===================
   
# Define the root logger with appender file
log4j.rootLogger = DEBUG, DB
#
## Define the DB appender
log4j.appender.DB=org.apache.log4j.jdbc.JDBCAppender
#
## Set JDBC URL
#Database name i mentioned here as test1
log4j.appender.DB.URL=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#
## Set Database Driver
log4j.appender.DB.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#
## Set database user name and password
log4j.appender.DB.user=sa
log4j.appender.DB.password=Admin@123
#
## Set the SQL statement to be executed.
log4j.appender.DB.sql=INSERT INTO LOGGER VALUES('%x','%d','%C','%p','%m')
#
## Define the layout for file appender
log4j.appender.DB.layout=org.apache.log4j.PatternLayout
#
#

Attach the log4j and sqljdbc.jar files in build path.





Run SaveLLogsToDB.java you can see the logger messages by opening the DataBase.

3 September 2017

Method Overriding VS Method Hiding

We Know that the Polymorphism is of two types
1.Static
2.Dynamic

In Dynamic Polymorphism the method which executes will be decided based on the object stored in the reference variable.

This is regarding instance methods

public class Animal {
    public void foo() {
        System.out.println("Animal");
    }
}

public class Cat extends Animal {
    public void foo() { // overrides Animal.foo()
        System.out.println("Cat");
    }
}

Then the following will happen:

class Test{

public static void main(String args[]){
Animal a = new Animal();
Animal b = new Cat();
Animal c = new Cat();
Animal d = null;

a.foo(); // prints Animal
b.foo(); // prints Cat
c.foo(); // prints Cat
d.foo(): // throws NullPointerException
    }
}

Instance methods, which are polymorphic and are thus overridden. The method called depends on the concrete, run time type of the object:

But for static methods it won't work.
The static methods will executes as follows....

public class Animal {
    public static void foo() {
        System.out.println("Animal");
    }
}

public class Cat extends Animal {
    public static void foo() { // overrides Animal.foo()
        System.out.println("Cat");
    }
}

class Test{

public static void main(String args[]){
Animal a = new Animal();
Animal b = new Cat();
Cat c = new Cat();
Animal d = null;

a.foo(); // prints Animal
b.foo(); // prints Animal
c.foo(); // prints Cat
d.foo(): // throws NullPointerException
      }
}

Here, Cat.foo() is said to hide Animal.foo(). Hiding does not work like overriding, because static methods are not polymorphic.
This is called Method Hiding Concept.

Calling static methods on instances rather than classes is a very bad practice, and should never be done.

23 July 2017

SOAP Web Services Example Using JAX-WS

Here is an Example for SOAP Web Services using JAX-WS

The Project Architecture is like this



Its a normal Java Project:
From Eclipse file--new--java project--SoapWSProj
And you know how to create the packages, classes etc. It has no external jars included.

ws.Demo.java

package ws;

import javax.jws.*;

@WebService
public interface Demo {

@WebMethod
public String helloWorld();

@WebMethod
public String hi(String name);

}

ws.DemoImpl



 * ProductWS.java

package ws;

import java.util.List;

import javax.jws.WebMethod;
import javax.jws.WebService;

import entities.Product;

@WebService
public interface ProductWS  {

@WebMethod
    public Product find() ;

@WebMethod
public List<Product> findAll();
}









2 July 2016

Java Introduction

Java




Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!


 Java is free to download. Get the latest version at java.com. or from www.oracle.com/technetwork/java/index.html


If you are building an embedded or consumer device and would like to include Java, please contact Oracle for more information on including Java in your device




Gosling is generally credited with having invented the Java programming language in 1994. He created the original design of Java and implemented the language's original compiler and virtual machine. Gosling traces the origins of the approach to his early graduate-student days, when he created a pseudo-code (p-code) virtual machine for the lab's DEC VAX computer, so that his professor could run programs written in U C SD Pascal. Pascal compiled into p-code to foster precisely this kind of portability. In the work leading to Java at Sun, he saw that architecture-neutral execution for widely distributed programs could be achieved by implementing a similar philosophy: always program for the same virtual machine.
For his achievement the National Academy of Engineering in the United States elected him as a Foreign Associate member. He has also made major contributions to several other software systems, such as NeWS and Gosling Emacs. He co-wrote the "bundle" program, a utility thoroughly detailed in Brian Kernighan and Rob Pike's book The Unix Programming Environment.

JAVA SetUp in System

JAVA ENVIRONMENT SET UP  =========================== In System Variables JAVA_HOME : C:\Program Files\Java\jdk1.8.0_144 JDK_HOME  : %J...