Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, January 21, 2013

Spring Security In Detail

How it works?

  1. AuthenticationManager(default impl - ProviderManager) is created with list of AuthenticationProviders (one such - AbstractUserDetailsAuthenticationProvider).


  1. An interceptor url is defined for j_spring_security_check with access true.


  1. An entry point can be URL (LoginUrlAuthenticationEntryPoint) or HttpResponse (BasicAuthenticationEntryPoint) which determines what needs to be shown to the user before authenticating.


  1. A login page with form action=”../../j_spring_security_check” and names j_username & j_password is created by Spring (Basic Authentication set) or by user. 


  1. And this login page url can be the entry point, so when anytime authorization expires or required, then it will redirect to that page.


  1. By default, UsernamePasswordAuthenticationFilter responds to above action URL and it looks for the names mentioned above in the HttpRequest.


  1. When the login form is submitted with username & password, it gets filtered by UsernamePasswordAuthenticationFilter.


  1. This filter creates an  Authentication (AuthenticationToken-UsernamePasswordAuthenticationToken) and calls the AuthenticationManager for authentication.


  1. Manager passes token (Authentication) to each of the providers in order declared.


  1. Each of the provider checks the type of token its looking for and if it matches, then just do the authentication (either uses retireveuser or just use cacheduser).


  1. If its authenticated successfully it returns a new Authentication object with all the details passed in and its set to the context available in SecurityContextHolder (SecurityContextHolder.getContext().setAuthentication(authResult)).

  1. On its failure, it just throws an AuthenticationException and that is set in the session attribute (SPRING_SECURITY_LAST_EXCEPTION).



Useful References

Wednesday, January 16, 2013

Hibernate Quick Reference

Hibernate Main Annotations

Entity - Defined for the class to denote it in the HQL
Table - Denotes the entity to be mapped to a table in DB
SecondaryTable - Mapping one entity to several tables in DB
Column - Defined for variables in an entity and mapped to a table's column in DB
Id - Indicates the primary key column of an entity
GeneratedValue - Provided to automatically generate the primary key values
- Strategy = GenerationType = TABLE, SEQUENCE, IDENTITY
TableGenerator(JPA) - Generates based on a 2 column key-value table
SequenceGenerator(JPA)- Generates based on the SEQ object in DB (only few DBs supports)
IdentityGenerator(JPA) - Generates based on Identity a database system property (only few DB supports)
GenericGenerator(Hib) - Specify custom generator
Embeddable - Defined for the class which can be added as a key in another entity
EmbeddedId - Denotes that the field is a key from another Embeddable entity (ex Address for Person entity)

Enumerated - Used to persist the enums (Ordinals/schema/table/catalog/column/type/String)
Proxy -
Cascade -

OneToOne -
OneToMany -
ManyToOne -
ManyToMany -
JoinColumn -
JoinTable -
PrimaryKeyJoinColumn -
MapKey -
MapKeyJoinColumn -

Hibernate Inheritance


Inheritance - Defines the inheritance strategy for the entities
InheritanceType - JOINED, SINGLE_TABLE, TABLE_PER_CLASS

JOINED - creates separate table for each class but have a joined primary key
SINGLE_TABLE - maintains only one table for all the parent child but differentiates based on discriminators
TABLE_PER_CLASS - Creates separate table for each parent child but have discriminators to associate

DiscriminatorColumn - Column used to join parent and child tables (name & type)
DiscriminatorValue - Value that separates the joined parent/child tables

Hibernate Criteria

createCriteria - creates and returns criteria for that Session for that entity
add() - applies the given criterion to the criteria
- EXPRESSION, RESTRICTIONS
addOrder() - adds ORDER to the criteria
setMaxResults() - sets the limit or max results the criteria can return
setFirstResult() - sets the initial start number for the results (used in pagination)

Hibernate Fetch

Fetch - Retrieves the persisted data based on FetchMode
FetchMode - JOIN, SELECT, SUBSELECT

Join - Disables lazy load and performs a join when fetching A it fetches B which has a relationship with A
Select - Enables lazy loads the related collections, individual select queries
SubSelect - Loads the related collections inside a subselect statement
BatchSize - Used to restrict returned size of collections (uses select in statement)

Hibernate Filter


FilterDef - Definition for the filters that needs to enabled on the session (using enableFilter()) (name & collection of @ParamDefs)
ParamDef - Defines the parameter for the filter (name & type)
Filter - Applies the filter to gettermethod/relationship column (name & condition)

Hibernate Cache

First level cache - Session class level cache
Secondary cache - SessionFactory level cache, means between sessions it can maintain the cache
Query cache - Cache contents of a query resultset, used in repeated execution of same query

Cache -
CacheConcurrencyStrategy - READ_ONLY, READ_WRITE

Hibernate Search

Indexed -
Field -

Others

list() vs iterate() - iterate() will be slower when the collection is not in session/second-level cache

Friday, May 18, 2012

OpenID (Authentication) & OAuth (Authorization)


OpenID = using login credentials from an OpenID provider (Google) to login to another application (Stack Overflow)

Definition
The OpenID protocol enables websites or applications (Consumers) to grant access their own applications by getting an authentication through another service or application (Provider), without requiring Users to maintain a separate account/profile with the Consumers.

Details
    OpenID Providers (Whose service we use to authenticate an user)
        google.com
        myopenid.com
        yahoo.com
    OpenID RelyingParty (Who uses OpenID as their authentication)
        mywebsite.com

Java Implementation
    JOpenID(http://code.google.com/p/jopenid/)        -    lightweight
    openid4java(http://code.google.com/p/openid4java/)    -    documented

References

REST Authentication with OpenID



OAuth = Allowing an application (TwitPic) to act on your behalf to and access information from an application that you use (Twitter)

Definition
The OAuth protocol enables websites or applications (Consumers) to access Protected Resources from a web service (Service Provider) via an API, without requiring Users to disclose their Service Provider credentials to the Consumers.

Details
    OAuth Provider     - Server Side (Who secures their service when exposed outside)
        Yahoo
        Google
        Twitter
    OAuth Consumer    - Client Side (Who authenticate their users with Provider to consume data from Provider)
        mywebsite.com

Java Implementation 
Clientside implementation
       Scribe(https://github.com/fernandezpablo85/scribe-java)               - lightweight
Both Serverside & Clientside implementation support

Please comment if anything I understood is wrong, so that I can correct the post & myself. :)

Friday, April 20, 2012

Cobertura Setup in MultiModule Maven With Jenkins (Draft)


Why we need a code coverage analysis for functional testing?
Reason is simple, tests which are generated out of a requirement specification just tests the functionality and satisfy when it meets the acceptance criteria. But when you see the overall tests which are resulted for the application, you can see lot of dependencies which are never tested at all.
Coverage analysis gives you a very solid statistics saying that these are the tests performed in the system and these are the statements or branches which are executed and these are not at all touched. This will help in tremendously improving the overall testcases which are written for the whole system by covering the untouched by analyzing the coverage report.
 
Out of Scope
Scope
Things Used
Eclipse Project Creation
Maven configurations
Sample Project
Maven Initial Setup
Instrumenting Code
Cobertura
JUnit Selenium Tests
Jenkins configurations
Maven
Cobertura Competencies


JUnit




Jenkins


STEP 1 : Create a simple multi-module maven web project to try it or use the one which you want to report coverage
Fig 1
  • Take a help from the maven example here to create a multi-module maven web project
  • Considered Fig 1 as a simple structure of such multi-module web project
  • Cobertura module - specifically added to generate the coverage report






STEP 2 : Modify the pom files to do the instrumentation of the codes


 do-instrumentation
 
  
   
    org.codehaus.mojo
    cobertura-maven-plugin
    ${cobertura.plugin.version}
    
    
    
     
      instrument-code
      process-classes
      
       instrument
      
      
       true
      
     
    
   
  
 
 
  
   net.sourceforge.cobertura
   cobertura-runtime
   ${cobertura.version}
   provided
   pom
  
 


STEP 3 : Include the necessary dependencies

STEP 4 : Have a separate module for merging & generating the report out of cobertura ser files

STEP 5 : Build the whole project to get the instrumented jars & war

STEP 6 : Deploy the war and run whatever tests you want to run on the application

STEP 7 : Run the Cobertura sub module with the location of ser file and generate the reports

STEP 8 : Give all the above tasks from 4 - 6 to Jenkins


Monday, June 1, 2009

Adding a JPanel in JTable's cell

Following sample code displays a JTable with 2 rows and a sincle column.
Each cell containing a JPanel with two JButtons and each of it is linked to its own action.

PS : Setting tool tips for the buttons inside JPanel in each cell is not possible directly. It may be achieved by calculating the static position of each buttin and compare it with the mouse position and show a tooltip.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

public class JButtonTableExample extends JFrame {

public JButtonTableExample() {
super( "JButtonTable Example" );

DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector( new Object[][] { {"1" }, {"2" } }, new Object[] {"Buttons" } );

JTable table = new JTable( dm );
table.getColumn( "Buttons" ).setCellRenderer( new PanelRenderer() );
table.getColumn( "Buttons" ).setCellEditor( new PanelEditor( new JCheckBox() ) );
JScrollPane scroll = new JScrollPane( table );
table.setRowHeight( 30 );
getContentPane().add( scroll );
setSize( 400, 150 );
setVisible( true );
}

public static void main( String[] args ) {
JButtonTableExample frame = new JButtonTableExample();
frame.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e ) {
System.exit( 0 );
}
} );
}

class PanelRenderer extends JPanel implements TableCellRenderer {

public PanelRenderer() {
setOpaque( true );
init();
}

private void init() {
setLayout( new FlowLayout( FlowLayout.CENTER, 5, 0 ) );
add( new JButton( "A" ) );
add( new JButton( "B" ) );
}

public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column ) {
if ( isSelected )
{
setForeground( table.getSelectionForeground() );
setBackground( table.getSelectionBackground() );
} else
{
setForeground( table.getForeground() );
setBackground( UIManager.getColor( "Button.background" ) );
}
return this;
}
}

class PanelEditor extends DefaultCellEditor {
protected JPanel panel;

protected JButton button1;

protected JButton button2;

public PanelEditor( JCheckBox checkBox ) {
super( checkBox );
panel = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 0 ) );
button1 = new JButton( "1" );
button1.setOpaque( true );
button1.setActionCommand( "Action1" );
button1.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
JOptionPane.showMessageDialog( button1, button1.getText()
+ ": Ouch!" );
fireEditingStopped();
}
} );
button2 = new JButton( "2" );
button2.setOpaque( true );
button2.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
JOptionPane.showMessageDialog( button2, button2.getText()
+ ": Ouch!" );
fireEditingStopped();
}
} );
panel.add( button1 );
panel.add( button2 );
}

public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column ) {
if ( isSelected )
{
button1.setForeground( table.getSelectionForeground() );
button1.setBackground( table.getSelectionBackground() );
} else
{
button1.setForeground( table.getForeground() );
button1.setBackground( table.getBackground() );
}
return panel;
}
}
}

Tuesday, September 2, 2008

Easy drag and drop in JList using MouseMotionListener without using TransferHandlers

Easy way to drag and drop in JList is to use MouseMotionListeners rather than using TransferHandlers.

Following is a demo program displays list box in which the order of the items can be changed by dnd.


public class DragDropDemo extends JPanel {

int index = -1;
String value = "";
JList list;
JScrollPane listScroll;
MouseDragDropListener mouseDragDropListener;
DefaultListModel listModel = new DefaultListModel();

public DragDropDemo() {
listModel.addElement( "0 (list 1)" );
listModel.addElement( "1 (list 1)" );
listModel.addElement( "2 (list 1)" );
listModel.addElement( "3 (list 1)" );
listModel.addElement( "4 (list 1)" );
listModel.addElement( "5 (list 1)" );
listModel.addElement( "6 (list 1)" );
list = new JList( listModel );
list.setSelectionMode(
ListSelectionModel.SINGLE_INTERVAL_SELECTION );
mouseDragDropListener = new MouseDragDropListener();
list.addMouseMotionListener( mouseDragDropListener );
list.addMouseListener( mouseDragDropListener );
listScroll = new JScrollPane( list );
setLayout( new BorderLayout() );
add( listScroll, BorderLayout.CENTER );
setPreferredSize( new Dimension(200,200) );
}

/**
* Create the GUI and show it. For thread safety, this method
* should be invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated( true );
JFrame frame = new JFrame( "DragDropDemo" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
DragDropDemo demo = new DragDropDemo();
frame.setContentPane( demo );
frame.pack();
frame.setVisible( true );
}

public static void main( String[] args ) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater( new Runnable() {
public void run() {
createAndShowGUI();
}
} );
}


/**
* Listener class to implement Drag and Drop functionality
*
*/
private class MouseDragDropListener extends MouseInputAdapter
{

/**
* Invoked when a mouse button is pressed on a component and then
* dragged
*/
public void mouseDragged(MouseEvent dragEvent)
{
if ( dragEvent.getSource() instanceof JList )
{
if ( dragEvent.getY() >= 0 &&
dragEvent.getY() <= list.getHeight()
&& dragEvent.getX() >= 0 &&
dragEvent.getX() <= list.getWidth() )
{
((JComponent) dragEvent.getSource()).
setCursor( new Cursor( Cursor.HAND_CURSOR ) );
drawField( value, dragEvent.getX(),
dragEvent.getY(), 150, 20 );
} else
{
((JComponent) dragEvent.getSource()).
setCursor( Cursor.getDefaultCursor() );
}
listScroll.repaint();
}
}

/**
* Method to draw a drag tooltip box at the given point
*/
private void drawField( String name, int xX, int yY, int width, int height )
{
final int x = xX;
final int y = yY;
final int w = width;
final int h = height;
final String fname = name;
Thread t = new Thread() {
public void run() {
Graphics g = list.getGraphics();
g.drawRect( x, y, w, h );
g.drawString( fname, x + 10, y + 15 );
}
};
t.start();
}

/**
* Invoked when a mouse button is pressed on a component
*
*/
public void mousePressed( MouseEvent pressEvent )
{
if ( pressEvent.getSource() instanceof JList )
{
JList list = (JList) pressEvent.getComponent();
index = list.getSelectedIndex();
if ( index >= 0 )
{
index = list.locationToIndex(
pressEvent.getPoint() );
}
value = list.getSelectedValue().toString();
list.setSelectedIndex( index );
}
}

/**
* Invoked when a mouse button is released on a component
* Passes the curIndex to moveToIndex method to move the
* dragginIndex.
*
*/
public void mouseReleased( MouseEvent releaseEvent )
{
if ( releaseEvent.getSource() instanceof JList )
{
if ( releaseEvent.getModifiers() > 16 )
{
return;
}
((JComponent) releaseEvent.getSource()).
setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) );
int curIndex = list.locationToIndex(
releaseEvent.getPoint() );
if ( curIndex == -1 )
{
if ( list.getModel().getSize()>0 )
{
if ( releaseEvent.getY() >=
list.getHeight() )
{
curIndex =
list.getModel().getSize() - 1;
} else if ( releaseEvent.getY()<=0)
{
curIndex = 0;
} else
{
curIndex = index;
}
} else
{
return;
}
}
if ( curIndex == index )
{
return;
}
moveToIndex( curIndex );
list.repaint();
listScroll.repaint();
}
}

/**
* Move the dragginField to the curIndex position.
* Where curIndex position is set to the index where mouse released.
*
* @param curIndex
*/
public void moveToIndex( int curIndex )
{
int listSize = list.getModel().getSize();
int moveToPos = curIndex + 1;
if ( moveToPos != 0 && value != null )
{
int newPos = moveToPos;
if ( moveToPos > 0 )
{
if ( newPos > listSize )
{
newPos = listSize;
}
newPos--;
} else if ( newPos < 0 )
{
newPos = 0;
}

listModel.remove( index );
listModel.add( newPos, value );
list.setSelectedIndex( newPos );
}
index = 0;
value = null;
}
}
}


Point to note:
When a MouseMotionListener is set for a Jlist component to perform drag and drop manually, then

list.setDragEnabled( true ); - to enable dragging in Jlist

should not be given. Since enabling this will consume the source mouse event in Jlist and that event will be sent to mousedrag event and hence will does nothing.

Monday, August 4, 2008

Override the focus traversal keys of a JTable

In a JTable, there are some predefined focus traversal keys. For example, CTRL+TAB to move out of JTable.

If that needs to be overrided with some other key combination the FocusTraversalKeySet should be replaced with a new set containing the new key combinations.

Following example shows the overriding of ForwardTraversalKey set with new KeySet containing CTRL+Z as the forward traversal key and also BackwardTraversalKey set with an EmptySet to disable all the backward traversals.


JTable table = new JTable(2,2);

TreeSet forwardSet = new TreeSet();

forwardSet.add(AWTKeyStroke.getAWTKeyStroke( KeyEvent.VK_Z,
InputEvent.CTRL_DOWN_MASK
| InputEvent.CTRL_MASK, false ) );

Set unmodifiableForwardSet =
Collections.unmodifiableSortedSet( forwardSet );

// To override the existing forward_traversal_key set
// with new unmodifiable set containing new
// key combination(CTRL+Z)
table.setFocusTraversalKeys(
KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
unmodifiableForwardSet );

// To disable all the backward traversal keys,
// an empty set can be used
table.setFocusTraversalKeys(
KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
Collections.EMPTY_SET );

Add rows on tabbing to a cell beyond the last cell

JTable by defaults selects the next cell when TAB is pressed. When the current selection is last cell, pressing tab selects the first cell. But here we want a new row to be inserted and selected the next newly created cell.

JTable table = new JTable(2, 2){
private final KeyStroke tabKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if(currentEvent instanceof KeyEvent){
KeyEvent ke = (KeyEvent)currentEvent;
if(ke.getSource()!=this)
return;
// focus change with keyboard
if(rowIndex==0 && columnIndex==0
&& KeyStroke.getKeyStrokeForEvent(ke).equals(tabKeyStroke)){
((DefaultTableModel)getModel()).addRow(new Object[getColumnCount()]);
rowIndex = getRowCount()-1;
}
}
super.changeSelection(rowIndex, columnIndex, toggle, extend);
}
};

Tweaking JTable Editing

There are two client properties supported by JTable which are related to editing.

JTable.autoStartsEdit:
The value is of type Java.lang.Boolean. This property tells whether JTable should start edit when a key is types. If the value of this property is null, it defaults to Boolean.TRUE. So this feature is enabled by default in JTable.

terminateEditOnFocusLost:
The value is of type Java.lang.Boolean. This property tells whether what to do when focus goes outside of JTable. It first tries to commit the changes in editor, if can't be committed then the changes are cancelled. If the value of this property is null, it default to Boolean.FALSE. So this feature is disabled by default in JTable.

You can enable this feature as follows:

table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);


I suggest to make this feature to be enabled for JTable.

Thursday, July 31, 2008

Code to set a Jtable column to fit its contents

Code to set a column to fit its contents,


TableColumn column = table.getColumnModel().getColumn(columnIndex);
int w = column.getWidth();
int n = table.getRowCount();
for (int i = 0; i < n; i ++)
{
TableCellRenderer r = table.getCellRenderer(i, this.columnIndex);
Component c = r.getTableCellRendererComponent(
table,
table.getValueAt(i, columnIndex),
false,
false,
i,
columnIndex);
w = Math.max(w, c.getPreferredSize().width);
}
column.setPreferredWidth(w);