Java Swing : Program to Count Number of Lines

/*
This program is used to count the number of lines for any content pasted.
*/

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;

public class AddDelButtonComplete implements ActionListener{

JTextArea text;

public static void main(String[] args) {
// TODO Auto-generated method stub
AddDelButtonComplete ad=new AddDelButtonComplete();
ad.start();
}
public void start(){

JFrame frame=new JFrame("*****Calculate No of Lines*****");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JLabel label=new JLabel("Paste your content here and click \"show\" to display no of lines of text : ");
label.setForeground(Color.BLUE);


System.out.println("Label's default layout Manager : "+label.getLayout());
JPanel panel=new JPanel();
JButton add=new JButton("Add");
add.setToolTipText("Click to Add Contents");

add.addActionListener(this);
JButton clear=new JButton("Clear");
clear.setToolTipText("Clears the contents displyed on the screen");
clear.addActionListener(this);

JButton del=new JButton("Show");
del.addActionListener(this);
System.out.println("Buttons default layout Manager : "+del.getLayout());

text=new JTextArea(35,105);
text.setLineWrap(true);

JScrollPane jsp=new JScrollPane(text);
System.out.println("Scroll's default layout Manager : "+jsp.getLayout());
jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
//panel.add(text);
panel.add(label);
panel.add(jsp);
System.out.println("Panel's default layout Manager : "+panel.getLayout());
// add scroller pane



frame.getContentPane().add(BorderLayout.CENTER,panel);
frame.getContentPane().add(BorderLayout.NORTH,add);
frame.getContentPane().add(BorderLayout.SOUTH,del);
frame.getContentPane().add(BorderLayout.EAST,clear);
System.out.println("Frames Default layout Manager : "+frame.getLayout());

//frame.setSize(350,300);
frame.setVisible(true);
frame.setMaximumSize(Toolkit.getDefaultToolkit().getScreenSize());
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

System.out.println(e.getActionCommand());
if(e.getActionCommand().equalsIgnoreCase("ADD")){
text.append("Clicked\n");
}
else if(e.getActionCommand().equalsIgnoreCase("SHOW"))
{


JOptionPane pane=new JOptionPane();
//pane.showMessageDialog(null, text.getText());
pane.showMessageDialog(null, "No of Lines : "+text.getLineCount());
//pane.setVisible(true);
}
else if(e.getActionCommand().equalsIgnoreCase("CLEAR"))
{
text.setText("Cleared Text");
}
}

}

Java Swing : Create Frame with Screen Size Dimension

JFrame frame=new JFrame();
frame.setSize((int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(), (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());

http://stackoverflow.com/questions/6777135/java-jframe-size-according-to-screen-resolution

Another alternative is to use:

JFrame frame=new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

Java provides switch statements with Strings in JDK 7 onwards

http://stackoverflow.com/questions/338206/switch-statement-with-strings-in-java

Software Release Paradigms: Alpha vs Beta vs RTM vs Preview vs RC vs RTM

I had this curiosity of Software Release

Alpha, Beta (can be broken into Internal vs. External)

CTP - Community Technology Preview - Not beta quality, not as wide-spread. Not necessarily feature-complete. Usually intended for partners who will build on top of the product.

Preview - Usually like a CTP.

RC (Release Candidate): Product believes it's ready to ship. One last chance for customers to provide feedback and find major blocking issues

RTM - Release to manufacturing. Final release of the product, the "Gold" release.

Source : http://stackoverflow.com/questions/736433/differences-between-ctp-alpha-beta-gamma-rtm-and-preview-for-software-releas

Selenium Grid : Starting a Hub and a Node using Grid



I had this small confusion around Selenium Standalone Server and Grid.
I have tried to summarize my understanding of starting Hub and multiple nodes.

Starting a hub using Selenium Grid:

java -jar selenium-server-standalone-2.40.0 -role hub -port 4443

-port 4443 is optional as the default port is 4444 and might be in use. The same output of successful server start is as below:

Apr 14, 2014 11:16:07 PM org.openqa.grid.selenium.GridLauncher main
INFO: Launching a selenium grid server
2014-04-14 23:16:08.871:INFO:osjs.Server:jetty-7.x.y-SNAPSHOT
2014-04-14 23:16:08.907:INFO:osjsh.ContextHandler:started o.s.j.s.ServletContextHandler{/,null}
2014-04-14 23:16:08.915:INFO:osjs.AbstractConnector:Started SocketConnector@0.0.0.0:4443

5555 is the default port that is used to open a default node. This can be used if you are planning to use virtual machine as each machine would have 5555 available.
However, if you want to try the same on your local machine with three nodes as instance you could the following

java -jar selenium-server-standalone-2.40.0 -role node -hub http://localhost:4443/grid/register -port 5555

java -jar selenium-server-standalone-2.40.0 -role node -hub http://localhost:4443/grid/register -port 5556
java -jar selenium-server-standalone-2.40.0 -role node -hub http://localhost:4443/grid/register -port 5556

Sample Server Startup log would look like :
Apr 14, 2014 11:21:16 PM org.openqa.grid.selenium.GridLauncher main
INFO: Launching a selenium grid node
23:21:17.554 INFO - Java: Sun Microsystems Inc. 20.5-b03
23:21:17.554 INFO - OS: Windows 7 6.1 x86
23:21:17.562 INFO - v2.40.0, with Core v2.40.0. Built from revision fbe29a9
23:21:17.640 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:5556/wd/hub
23:21:17.641 INFO - Version Jetty/5.1.x
23:21:17.642 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
23:21:17.643 INFO - Started HttpContext[/selenium-server,/selenium-server]
23:21:17.643 INFO - Started HttpContext[/,/]
23:21:17.645 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@1c92535
23:21:17.645 INFO - Started HttpContext[/wd,/wd]
23:21:17.648 INFO - Started SocketListener on 0.0.0.0:5556
23:21:17.648 INFO - Started org.openqa.jetty.jetty.Server@134bed0
23:21:17.649 INFO - using the json request : {"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"VISTA","seleniumProtocol":"Selen
ium","browserName":"*firefox","maxInstances":5},{"platform":"VISTA","seleniumProtocol":"Selenium","browserName":"*googlechrome","maxInstances":5},{"platform":"V
ISTA","seleniumProtocol":"Selenium","browserName":"*iexplore","maxInstances":1},{"platform":"VISTA","seleniumProtocol":"WebDriver","browserName":"firefox","maxI
nstances":5},{"platform":"VISTA","seleniumProtocol":"WebDriver","browserName":"chrome","maxInstances":5},{"platform":"VISTA","seleniumProtocol":"WebDriver","bro
wserName":"internet explorer","maxInstances":1}],"configuration":{"port":5556,"register":true,"host":"192.168.1.3","proxy":"org.openqa.grid.selenium.proxy.Defau
ltRemoteProxy","maxSession":5,"role":"node","hubHost":"localhost","registerCycle":5000,"hub":"http://localhost:4443/grid/register","hubPort":4443,"url":"http://
192.168.1.3:5556","remoteHost":"http://192.168.1.3:5556"}}
23:21:17.651 INFO - Starting auto register thread. Will try to register every 5000 ms.
23:21:17.651 INFO - Registering the node to hub :http://localhost:4443/grid/register

Remote webdriver instances would have to connect to :
http://locahost:5555/wd/hub
http://locahost:5556/wd/hub


Additional Information

While launching a node or hub look for the following in the console output
INFO: Launching a selenium grid server
INFO: Launching a selenium grid node

The command used for standalone server is
java -jar <sel.jar> -hub -port 4443

The command for starting a hub using Selenium Grid is
java - jar <sel.jar> -role hub -port 4443

Please note this change.

Regards,
Ajith Moni

J2EE: Distributed environment Containers, Persistance & Naming

J2EE Technologies
Web centric Programming
- Integration of servlets and JSP into enterprise applications.
Within an organization, or even when creating B2B links, clients may connect directly to business components in the shape of EJB over RMI or CORBA.

Maintaining the integrity of the data is provided by "Transactions and Persistence"

A Mode for Enterprise Computing
An n-tier, component-based, Web-friendly environment is needed.
What about detail - what specific functionality is needed to support such applications.

OMG,1989 formed specifications for Distributed Object Computing landscape, such as

  1. Common Object Request Broker Architecture(CORBA)
  2. the Internet Inter-Orb Protocol(IIOP) 
  3. and UML(unified modeling language)

A distributed component environment must provide "Containers" to manage the lifetime of components and assist in their deployment.

With RMI, a distributed leading mechanism is used.
With CORBA, there are lifecycle management services.
DCOM relies on objects controlling their own lifetimes.


Persistance

Storage of data for retrieval.
Example : ODMS and RDBMS

Naming

Distributed applications will be formed from components that reside on different machines.
Common Directory Object Services (COS) Naming Service
The COS naming service is widely used in Java-based distributed environments as a way of storing information about the location of remote objects.

X.500 - Storing Hierarchical information and an access protocol called the Directory Access Protocol(DAP).

LDAP - Lightweight version of X.500 that runs over TCP/IP

DNS - IP Internet Protocol that allows translation between hostnames and Internet addresses. DNS is used by all Internet clients such as Web Browsers.


J2EE: What is a Component

A Component is a unit of functionality that can be used within a particular framework.
Component framework, a container provides the components with certain standard services, such as communication and persistence.

The component principle applied to non-visual components also.

Distributed applications can be created from components.
Frameworks provide language independence.
Using CORBA, components in C can communicate with those written in OO languages such as Java and Smalltalk.

In the 3 tier environment, The functionality of the Data Access Logic layer would be split into multiple components.

Components can be purchased from third parties and integrated.

J2EE involves separation of functionality both by using layers and tiers and also the use of components within those layers(and objects within those components).

Presentational developers need not know anything about the business rules.
Any changes to any of the layers should not impact others.

Distributed Internet becomes the computer.





Send Email from Java Program using personal GMAIL Account POP


For POP Settings, please refer to :
https://support.google.com/mail/troubleshooter/1668960?hl=en&ref_topic=3397500#ts=1665119,1665162

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class PopSmtp {

public static void main(String[] args) {

final String username = "majith414@gmail.com";
//               I have 2 step authentication for gmail account
//
final String password = "jgasdgegndph12324safsavgzhvmbgvqxhw";


Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props,
 new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
 });

try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("majith414@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("majith414@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Ajith,"
+ "\n\n Test, please!");

Transport.send(message);

System.out.println("Done");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}

Java Mail : SMTP server to send mail with Java and gmail

You need to have SMTP Server listening on port : 25.

To check if you have the service on a windows machine. Use the command
C:\>telnet localhost 25

If you received a message such as
"Connecting To locahost...Could not open connection to the host, on port 25: Connect failed"

we might install an email server such as :
Mercury email server(also comes with WAMMP)
http://www.pmail.com/overviews/ovw_mercury.htm
Apache James
http://james.apache.org/

Sample Program to Test:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;



public class EMail {

public static void main(String[] args) {
// TODO Auto-generated method stub
String to="to_uname@gmail.com";
String from="from_uname@gmail.com";

String host="localhost";

Properties props=System.getProperties();

props.setProperty("mail.smtp.host", host);
props.setProperty("mail.user", "unaem");
props.setProperty("mail.password", "password");
Session session=Session.getDefaultInstance(props);

try
{
MimeMessage message=new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Java Mail - Test");
message.setText("Hi User,/n/nThis is a sample message/n/nRegards, Sent User");

Transport.send(message);
}
catch(MessagingException mex)
{
mex.printStackTrace();
}

}


}

Source: http://stackoverflow.com/questions/18781556/send-a-mail-with-java-and-gmail

JNDI Directory and Packages: LDAP Package

The javax.naming.ldap package contains classes and interfaces for using feature that are specific to the LDAPv3.

Most JNDI applications that use the LDAP will find the javax.naming.directory package sufficient and will not need to use the ldap package at all.

The ldap package is primarily used for those applications that need to use
"extended" operations, controls or notifications.

The LDAPContext interface represents a context for performing "extended" operations, sending request controls, and receiving response controls.

Source: http://docs.oracle.com/javase/tutorial/jndi/overview/dir.html

JNDI : Directory and Packages

The javax.naming.directory extends the javax.naming package to provide
functionality for accesssing directory services in addition to naming services.

The Directory Context

The DirContext interface represents a directory context.
DirContext also behaves as a naming context by extending the "Context" interface.

This means that a directory object can also provide a naming context.
It defines methods for searching and updating attibutes associated with a directory entry.

Attributes.

You can use getAttribtues() method to retrieve the attributes associated with a directory entry.
Searches:

DirContext contains methods for performing content based searching of the directory using the search() method.



Whata are the various JNDI Packages ?

The JNDI packages are divided into 5 packages:
javax.naming
javax.naming.directory
javax.naming.ldap
javax.naming.event.
javax.naming.spi

Naming

The javax.naming package contains of classes and interfaces for accessing naming services.

Context

The javax.naming package defines a Context interface,
which is the core interface for looking up, binding/unbinding,
renaming objects and creating and destroying  subcontexts.

Lookup

It is used to lookup the name of object and returns the object bound to that name.

Bindings:

Returns the enumeration of name to object bindings.
it is a tuple containing :
- name of the bound object
- name of the objects class
- and the object itself

List

returns enumeration of names containing an object's name
and the name of the object's class.

Name
an ordered sequence of zero or more components.

References

contains information on how to construct a copy of the object.

The Initial Context:

In JNDI, all naming and directory operations are performed relative to a context.
it provides a starting point for naming and directory operations.
Once you have an Initial context you can use to look up other contexts and objects.
Example:

DirContext context=new InitialDirContext();

Overview of JNDI and Architecture

JNDI is an API that provides naming and directory functionality to applications written in Java Programming Language.

Architecture:

The JNDI consists of an API and service provider Interface(SPI).
Java applications use the JNDI API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparantly, there by allowing the Java application using the JNDI API to access their services.

1) Java Application
2) JNDI API
3) Naming Manager
4) JDNI SPI(LDAP,DNS,NIS,NDS,RMI,CORBA)

The JDK includes service providers for the following  naming/directory services:

-LDAP
-Common Object Request Broken Architecture (CORBA)
- RMI - ( Remote Method Invocation )
- DNS ( Domain Naming Service )



Source : http://docs.oracle.com/javase/tutorial/jndi/overview/index.html

JDNI : Directory Services

Directory Services


A Directory is a connected set of directory objects. A directory service is a service that provides operations for creating, adding , removing, and modifying the attributes associated with objects in a directory.

Example of Directory Services:

Network Information Service - stores information related to machines, network, printers and users.

Oracle Directory Server- general purpose directory service based on the Internet Standard LDAP

Search Service

It is a way of looking up a for a directory object by supplying its name to the directory service
When you search, you can supply a query consisting of logical expressions in which you specificy the attributes attributes that the object or objects must have.

The query is called "search filter". This style of searching is sometimes called reverse lookup or context-based searching.

The directory search returns the objects that satisfy the search filter.

Example :
"All machines whose IP address starts with "192.X.X.X."

Java JDNI : Directory Concepts

A directory service associates names with objects.
It also associates objects with attributes.

directory service = naming service + objects containing attributes

Analogy:

Mapping a subscripber's name to his address and phone number.[Phone Directory]

Attibutes:

A directory object can have attributes.
A printer might be represented by a directory object that has attributes such as speed, resolution and color.
A user might be represented by a directory object with attributes such as user's e-mail address, telephone numbers, postal mail address etc.,

An attribute has an attribute identifier and a set of attribute values.
An attribute identifier is a "token" that identifies an attibute.
It is independent of its values.

Example :
Two different computers might have a "mail" attribute;
"mail" is the attribute identifier.
An attribute value is the contents of the attribute.

The email address, for example, might have
Attribute Identifier: Attribute Value
mail: john.smith@example.com

A directory is

Source: http://docs.oracle.com/javase/tutorial/jndi/concepts/directory.html

What is JNDI in java- Naming, Names, Binding & Context ?

JNDI stands for Java Naming and Directory Interface

The most popular directory service LDAP is used to demonstrate the use of JNDI to access the directory services.

Naming and Directory Concepts:

Naming Concepts:

A Naming service allows you to look up an object given its name.
Name - Object

A Naming service's primary function is to map people friendly names to objects, such as address
objects
identifiers
objects

Example : Internet Domain Name System(DNA) maps machine names to IP Addresses.
www.example.com => 192.168.0.1

A file system maps a filename to a file reference that a program can use

C:\test\test.xml=>File Reference

Names:
To look up an object in a naming system, you supply it the name of the object.
The naming system determines the syntax that the name must follow.

A name is made of components as in :

Naming
.
Naming System Component Separator Names
UNIX file system "/" /usr/hello
DNS "." sales.example.COM
LDAP "," and "=" cn=Moni Ajith, o=Example, c=US

Bindings:

The associatino of a name with an object is called a binding.
A filename is bound to a file.

The DNS contains bindins that map machine names to IP addresses.
An LDAP name is bound to an LDAP Directory.

Context

A Context is a set of name-to-object binding.
Every context has an associated naming convention .

Example

DNS - COM(context)->Example(SubContext)
LDAP - c=us(context)->o=Example(SubContext)

Summary
An LDAP Entry such as c=us, represents a context.
An LDAP entry named relative to another LDAP entry represents a subcontext.
For DNS domain Example.com, the DNS domain name Example is a subcontext of COM.

Source:http://docs.oracle.com/javase/tutorial/jndi/overview/index.html

Analytics