Month: January 2016

How to run external JAVA program by using ProcessBuilder

Posted on

java-logojava.lang.ProcessBuilder was introduced in Java 1.5 version, is used to create an Operating System Process. see Java API

Before going on example section, see ProcessBuilder attributes:-

 

Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.

Each process builder manages these process attributes:

  • a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves – on such a system a Java implementation might require commands to contain exactly two elements.
  • an environment, which is a system-dependent mapping from variables to values. The initial value is a copy of the environment of the current process (see System.getenv()).
  • a working directory. The default value is the current working directory of the current process, usually the directory named by the system property user.dir.
  • a source of standard input. By default, the subprocess reads input from a pipe. Java code can access this pipe via the output stream returned by Process.getOutputStream(). However, standard input may be redirected to another source using redirectInput. In this case, Process.getOutputStream() will return a null output stream, for which:
    • the write methods always throw IOException
    • the close method does nothing
  • a destination for standard output and standard error. By default, the subprocess writes standard output and standard error to pipes. Java code can access these pipes via the input streams returned by Process.getInputStream() and Process.getErrorStream(). However, standard output and standard error may be redirected to other destinations using redirectOutput andredirectError. In this case, Process.getInputStream() and/or Process.getErrorStream() will return a null input stream, for which:
    • the read methods always return -1
    • the available method always returns 0
    • the close method does nothing
  • a redirectErrorStream property. Initially, this property is false, meaning that the standard output and error output of a subprocess are sent to two separate streams, which can be accessed using the Process.getInputStream() and Process.getErrorStream() methods.If the value is set to true, then:
    • standard error is merged with the standard output and always sent to the same destination (this makes it easier to correlate error messages with the corresponding output)
    • the common destination of standard error and standard output can be redirected using redirectOutput
    • any redirection set by the redirectError method is ignored when creating a subprocess
    • the stream returned from Process.getErrorStream() will always be a null input stream

Following example demonstrate how to run external Java program, Same way we can run any external program which must be set in OS environment.

Before running this program on your machine, make sure that JAVA_HOME must be set in your OS environment.


package com.itexpert.exam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JavaProcessBuilder {
/**
* Provide absolute JAVA file path
*/
private static final String JAVA_FILE_LOCATION = "D:\\Test.java";

public static void main(String args[]) throws IOException{
String command[] = {"javac",JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command);

Process process = processBuilder.start();
/**
* Check if any errors or compilation errors encounter then print on Console.
*/

if( process.getErrorStream().read() != -1 ){
print("Compilation Errors",process.getErrorStream());
}
/**
* Check if javac process execute successfully or Not
* 0 - successful
*/
if( process.exitValue() == 0 ){
process = new ProcessBuilder(new String[]{"java","-cp","d:\\","Test"}).start();
/** Check if RuntimeException or Errors encounter during execution then print errors on console
* Otherwise print Output
*/
if( process.getErrorStream().read() != -1 ){
print("Errors ",process.getErrorStream());
}
else{
print("Output ",process.getInputStream());
}

}
}

private static void print(String status,InputStream input) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(input));
System.out.println("************* "+status+"***********************");
String line = null;
while((line = in.readLine()) != null ){
System.out.println(line);
}
in.close();
}

}

External Java Program source code below:-


public class Test {
public static void main(String args[]){
System.out.println("Hello, How are you !!!");
}
}


Output if Compilation done successfully


************* Output ***********************
Hello, How are you !!!

Suppose, if we pass incorrect file “Test1” through command[] object which does not exist in your given path then-


************* Compilation Errors***********************
avac: file not found: D:\Test1.java
Usage: javac 
use -help for a list of possible options

Suppose, if any compilation errors exist in Java file then-


************* Compilation Errors***********************
:\Test.java:3: error: cannot find symbol
		System.out.printlna("Hello, How are you !!!");
		          ^
  symbol:   method printlna(String)
  location: variable out of type PrintStream
1 error

Thanks !!

Advertisements

Difference between WHERE vs HAVING clause in SQL

Posted on Updated on

MySQLThis is frequently asked questions in Database interview , .Net interview and Java Interview. Developer should know the basic differences of these two clauses in SQL.

Where” clause is used for selection a row or set of rows from table, base on criteria like primary key or other column fields table rows get retrieved. It can be used in update, delete and select statement base on the criteria or more than one criteria.

Having” clause used with aggregate function that is work over Group by selection, Having clause always followed by Group by clause or it does not perform like where clause. It boosts the better performance by avoiding unnecessary column sorting and grouping

Aggregate Function below:- 

  • AVG() – Returns the average value
  • COUNT() – Returns the number of rows
  • FIRST() – Returns the first value
  • LAST() – Returns the last value
  • MAX() – Returns the largest value
  • MIN() – Returns the smallest value
  • SUM() – Returns the sum

Difference between WHERE vs HAVING

  1. The WHERE clause specifies the criteria which individual records must meet to be selected by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.
  2. The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.
  3. The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions.
  4. The WHERE clause is used in any DML form like Select, Update and Delete Query while Having clause can be only used with Select statement.
  5. The Where clause can be applied individual row while Having clause can be applied only a group of rows.

Note: Having and Where clause can not be used together.

 

$routeProvider vs $stateProvider in AngularJs

Posted on Updated on

angularjs$routeProvider vs $stateProvider in AngularJs

See overview and differences between $routeProvider and $stateProvide routing modules. Each module has some cons and pros are given below.

$routeProvider  :-

It exposes APIs that allow you to define routes for your application. It works on specifics URLs to a Controller and assign a Template page. Generally, template page is rendered inside <ng-view> elements on parent page. We can embed URLs in two way –  ng-href or href attribute.

Html code below :- 

<ul class="nav navbar-nav">
     <li><a href ng-href="/home">Home</a></li>
     <li><a href ng-href="/contact">Contact</a></li>
</ul>

Below are basic $routeProvider Implementation snippet :-

routeProvider-1
limitation:-

  • The Page can contain only one ng-view on Page.
  • $routeProvider don’t know about Parent/Child relationship.

It’s simple and easier to use.

$stateProvider:-

It works similar to $routeProvider but it purely focus on state rather than URLs. We can leverage lot of feature by using UI-Route provides:-

  • You can have multiple ui-view on single page
  • Various view can be nested in each other and maintain by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Other way you could relative routing using only @ to change ui-view="some", This will replace the ui-view rather than checking it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

Doing this, you have to download angular-route-ui.js file.

Below have some Html code that defined different routing and routing scope like child and parent relationship.

<ul class=”nav navbar-nav”>
<li><a ui-sref=”home“>Home</a></li>
<li><a ui-sref=”home.listOfBook“>Books</a></li>
<li><a ui-sref=”home.login“>Login</a></li>
<li><a ui-sref=”about“>About Us</a></li>
</ul>

In about html page having two named section “columnOne” and “columnTwo” and each section has a Controller and View template attached in angular config( see Javascript ) to render the output inside respective     <ui-view> area.

aboutPage.html

stateProvider-html

Below are basic $stateProvider Implementation snippet :-

stateProvider-1

 

ref :

https://github.com/angular-ui/ui-router/wiki
https://docs.angularjs.org/tutorial/step_07
Thanks !!!

 

How to Implement JMS with Tomcat – Durable Subscription Example

Posted on Updated on

java-logoIn this A Durable Subscription Example, we will see how to implement JMS with Tomcat.  read What is JMS in previous article.

Tomcat doesn’t supports JMS itself but using some external library ( ActiveMQ ) we can accomplish it. here we use JMS vendor – ActiveMQ

so, before getting started, download couple of libraries and put it into Tocat/lib directory and Project classpath.

or Copy and paste below Maven Dependencies in your pom.xml file:-

 <dependency>
 <groupId>commons-logging</groupId>
 <artifactId>commons-logging</artifactId>
 <version>1.2</version>
 </dependency>
 <dependency>
 <groupId>org.apache.activemq</groupId>
 <artifactId>activemq-all</artifactId>
 <version>5.11.1</version>
 </dependency>

Next, add the resource below to conf/server.xml:

<GlobalNamingResources>
 <Resource name="ConnectionFactory" auth="Container"
 type="org.apache.activemq.ActiveMQConnectionFactory" description="JMS
 Connection Factory " factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 brokerurl="tcp://localhost:61617"
 brokerName="ActiveMQBroker"
 useEmbeddedBroker="false"/>

 <Resource name="jms/topic/ITExpertsTopic" auth="Container"
 type="org.apache.activemq.command.ActiveMQTopic" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 physicalName="APP.JMS.TOPIC" />

 <Resource name="jms/queue/ITExpertsQueue" auth="Container"
 type="org.apache.activemq.command.ActiveMQQueue" factory="org.apache.activemq.jndi.JNDIReferenceFactory"
 physicalName=" APP.JMS.QUEUE" />

 </GlobalNamingResources>

Next, add this code to context.xml:

<ResourceLink global="jms/ConnectionFactory" name="jms/ConnectionFactory" type="javax.jms.ConnectionFactory"/>
<ResourceLink global="jms/topic/ITExpertsTopic" name="jms/topic/ITExpertsTopic" type="javax.jms.Topic"/>
<ResourceLink global="jms/queue/ITExpertsQueue" name="jms/queue/ITExpertsQueue" type="javax.jms.Queue"/>

Next, We need to add ActiveMQ props into tomcat class path:

set JAVA_OPTS=-Dwebconsole.type=properties -Dwebconsole.jms.url=”tcp://localhost:61617″ -Dwebconsole.jmx.url=”service:jmx:rmi:///jndi/rmi://localhost:1099/ jmxrmi”

Below are code snippet of A Durable Subscription Example :-

MessageProducerClient.Java

package com.itexperts.jms;
/**
 * 
 * @author #Ajay
 *
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.activemq.broker.BrokerService;

public class MessageProducerClient {

 public static Properties getProp() {
 Properties props = new Properties();
 props.setProperty(Context.INITIAL_CONTEXT_FACTORY,
 "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
 props.setProperty(Context.PROVIDER_URL, "tcp://localhost:61617");
 return props;
 }

 public static void initBroker() throws Exception {
 BrokerService broker = new BrokerService();
 // configure the broker
 broker.addConnector("tcp://localhost:61617");
 broker.start();
 }

 public static void main(String args[]) {

 Connection connection = null;
 try {
 initBroker();
 InitialContext jndiContext = new InitialContext(getProp());
 ConnectionFactory connectionFactory = (ConnectionFactory) jndiContext
 .lookup("ConnectionFactory");
 connection = connectionFactory.createConnection();
 connection.setClientID("durable");
 Session session = connection.createSession(false,
 Session.AUTO_ACKNOWLEDGE);
 Destination destination = session
 .createTopic("jms/topic/ITExpertsTopic");
 MessageProducer producer = session.createProducer(destination);
 TextMessage msg = session.createTextMessage();
 msg.setText("Hello, This is JMS example !!");
 BufferedReader reader = new BufferedReader(new InputStreamReader(
 System.in));
 while (true) {
 System.out
 .println("Enter Message to Topic or Press 'Q' for Close this Session");
 String input = reader.readLine();
 if ("Q".equalsIgnoreCase(input.trim())) {
 break;
 }
 msg.setText(input);
 producer.send(msg);
 }
 } catch (JMSException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 } catch (NamingException e) {
 e.printStackTrace();
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (connection != null) {
 connection.close();
 }
 } catch (JMSException e) {
 e.printStackTrace();
 }
 }

 }
}

MessageReceiverClient.Java


package com.itexperts.jms;

import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 
 * @author #Ajay
 *
 */
public class MessageReceiverClient {
 protected static final String url = "tcp://localhost:61617";

 public static void main(String args[]) {

 TopicConnection connection = null;
 try {
 ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
 url);
 connection = factory.createTopicConnection();
 connection.setClientID("durable");
 connection.start();
 MessageConsumer consumer = null;
 Session session = connection.createTopicSession(false,
 Session.AUTO_ACKNOWLEDGE);
 Topic topic = session.createTopic("jms/topic/ITExpertsTopic");
 consumer = session.createDurableSubscriber(topic, "mySub");
 // consumer.setMessageListener(new ReceiverListener());

 // System.out.println(" Waiting for Message ...");
 // while(true){
 // Thread.sleep(1000);
 // }
 while (true) {
 TextMessage message = (TextMessage) consumer.receive();
 System.out.println(message.getText());
 }
 } catch (Exception e) {
 e.printStackTrace();
 } finally {
 try {
 if (connection != null) {
 connection.close();
 }
 } catch (JMSException e) {
 e.printStackTrace();
 }
 }

 }

}

Compile and run these two Java files separately in two command prompt.

Here you will see how durable topics works when a Sender/Producer send a bunch of messages while  Subscriber/ Receiver is not yet active.

Step 1: Compile and run MessageProducerClient.Java file. Send some message to durable using command prompt.

Step 2: Compile and run MessageReceiverClient.Java file. When you run this file then all messages that are retain on Destination Durable Topic get started consuming and print on console.

 

What is JMS – Java Message Service

Posted on Updated on

java-logoIn this tutorial, we will see the overview of JMS and it’s implementations. JMS was developed by Sun Microsystems that allows a Java programming language to communicate with other messaging systems. Mostly JMS enables in distributed application where two or more Software Components or Applications pointing to same Destination( i.e Queue/Topic/Durable) in the way to communicating to each other by sending or reading the message subsequently.

Suppose, A component sends a message to a destination, and the recipient can retrieve the message from the destination. However, the sender and the receiver do not have to be available at the same time in order to communicate. In fact, the sender does not need to know anything about the receiver; nor does the receiver need to know anything about the sender. The sender and the receiver need to know only which message format and which destination to use. In this respect, Durable Topic can be helpful which retains the messages while the Subscriber is not active. Once the Subscribers get activated then messages can be received from durable.

What is JMS?

Java message service enables loosely coupled communication between two or more systems. It provides reliable and asynchronous form of communication. There are two types of messaging models in JMS.

Point-to-Point Messaging Domain

Applications are built on the concept of message queues, senders, and receivers. Each message is send to a specific queue, and receiving systems consume messages from the queues established to hold their messages. Queues retain all messages sent to them until the messages are consumed by the receiver or expire. Here there is only one consumer for a message. If the receiver is not available at any point, message will remain in the message broker (Queue) and will be delivered to the consumer when it is available or free to process the message. Also receiver acknowledges the consumption on each message.

Publish/Subscribe Messaging Domain

Applications send message to a message broker called Topic. This topic publishes the message to all the subscribers. Topic retains the messages until it is delivered to the systems at the receiving end. Applications are loosely coupled and do not need to be on the same server. Message communications are handled by the message broker; in this case it is called a topic. A message can have multiple consumers and consumers will get the messages only after it gets subscribed and consumers need to remain active in order to get new messages.

 

Message can be consumed either two ways:-

  • Synchronously: A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.
  • Asynchronously: A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message.

Building Block of JMS Application are:-

The JMS API Programming Model

Diagram of the JMS API programming model: connection factory, connection, session, message producer, message consumer, messages, and destinations

First we need to create a connection object using the ActiveMQConnectionFactory factory object. Then we create a session object.  Using the session object we set the message broker (Queue) and create the message sender object.

Below are some JMS Implementation in JAVA:-

AngularJS Bootstrap Model + ngAnimate with Login Example

Posted on

angularjs

This is another AngularJS with Bootstrap Login example, In this article we covered animation, broadcasting and AngularJS directive.

In the below example demonstration, we will see how to implement Bootstrap Model in AngularJS having some animation effects. In the Home page there is a Login option at right side that will  trigger on onClick event and displayed a popup Login Model Form. We applied some validation like  minLength=4 and required on Login Form elements. Once the Form Login validation is done then it send to Controller to process and authenticate “username” & “password” using some backend service.  Here we don’t implement any backend service ( will disuss in next article ) for authentication but we simply pull out user information from Login window and broadcast to another controller ( baseController) that user is authencated so Login option on navigator bar to be changed to User Info drop down.

During the transition of Model window we applied simple effects ( fade in& out) on Model but you can get lots of transition effects on internet and you can do apply.

Also we created a Directive for “FormElement” which is of course replacement of redundent html code.

Require Javascripts :-

https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js
http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js
http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js
http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.0.2.js
<link href=”http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css&#8221; rel=”stylesheet”>

here we have created a simple html page, containing a navigation bar at top. A Login Option is given in right side of nav bar.

Render Html page below:-

formModel-output1

Login Model Html :-

formModel-login

Angular Javascript :-

formModel-JS

 

Simple animation CSS :-

formModel-css

When Login is clicked on nav bar then a Login Popup window will be rendered. Initially Submit button is diable. It get enabled only if all validation get true.
formModel-output3

Next, when User enter valid “username” and “password”  and click on Login button then  Home page will be rendered with some User information and Logout button in drop down section. see in next screen-

 

formModel-output5

 

 

 

 

 

formModel-output4

Please find complete code here.
Thanks !!

AngularJS Form Validation with Bootstrap

Posted on Updated on

angularjs

 

 

 

In this article, we will see Angular Validation with bootstrap Framework, Angular provide some build-in validtion that make earier to do lots of stuff in client side. In below example we create a simple User Form that take some input from Client and validate using some angular ( custom directive validation ) and bootstrap validation together.

Although, AngularJS validation works on HTML 5 validation.

Custom Validation using Directive :-

Here, we create a directive i.e ngCompare that compare on Cofirm Password field with “password” field if these two fields are matched then it’s allow to proceed to form submition otherwise error message will be displayed either inline or prompt msg.

Create a Directive i.e ngCompare that compare two fields ( password with comfirm password)

angular-userForm-directive

 

Angular Validation properties  here :-

  1. $valid : It is a boolean property that tells whether the form or it’s inputs are valid or not. If all containing form and controls are valid, then it will be true, otherwise it will be false.
  2. $invalid : It is a boolean property that tells whether the form or it’s inputs are invalid or not. If at least one containing form and control is invalid then it will be true, otherwise it will be false.
  3. $dirty : It is a boolean property that is actually just reverse of pristine i.e. it tells whether the form or it’s inputs are modified by the user or not. If the form or it’s inputs are modified by the user, then it will be true, otherwise it will be false.
  4. $touch : the control has been blurred
  5. $error :This is an object hash which contains references to all invalid controls or forms. It has all errors as keys: where keys are validation tokens (such as required, url or email) and values are arrays of controls or forms that are invalid with given error. For a control, If a validation fails then it will be true, otherwise it will be false.
  6. $pristine:– It is a boolean property that tells whether the form or it’s inputs are unmodified by the user or not. If the form or it’s inputs are unmodified by the user, then it will be true, otherwise it will be false.

Angular Form Methods  :-

  1. $addControl() : This method registers a control with the form.
  2. $removeControl() :This method remove a control from the form.
  3. $setDirty() : This method set the form to Dirty state.
  4. $setValidity() : This method set the validity of a form control.
  5. $setPristine() : This method set the form to its pristine state.

angular-userForm

How Validation work here :-

Displaying error message when validation get failed.

angular-userForm-output-error

 

Once Validation compated, ready for Form submition :-

angular-userForm-output

See complete code here.