Util Method to get all attributes printed in System.out.println()

This small util override is to allow developers to view all instance variable values as a CSV format in Java. It is similar to the one seen as var_dump in PHP:

    @Override
    public String toString() {
        Field[] fields = this.getClass().getDeclaredFields();
        StringBuilder sbNote = new StringBuilder();
        sbNote.append("{");
        for (int i = 0; i < fields.length; i++) {
            try {
                sbNote.append(fields[i].getName() + " - " + fields[i].get(this)+", ");
            } catch (java.lang.IllegalAccessException e) {
                System.out.println(e);
            }
        }
        sbNote.append("}");
        return sbNote.toString();
    }

override the toString() method to the above code to get a comma separated description enclosed in {}

Another useful library is the Apache commons –

public String toString() {
       return ToStringBuilder.reflectionToString(this);
}

How to Left pad Zeros to integer to get String in Java

The below is the code as to how to add 0 Padding to the left of an integer to format it to string:

import java.text.DecimalFormat; 

public String padZeros(int i) { 
     DecimalFormat df = new DecimalFormat("00"); 
     return df.format(start); 
}

Change the Number format instead of “00” to any other format for getting more paddings.

How to do an LDAP Search of Various fields

Requirement: retrieving various values such as Description, Office, etc. from LDAP after authentication.

An LDAP client retrieves attribute values (referred to as “fields” in the question) by transmitting a search request to the server and then reading the server’s response. A search request consists of at a minimum the following components:

  • base DN – the object at which to begin the search. No objects above the base DN are returned
  • scope – the scope of the search; this is base, one, or subtree
  • filter – a filter which limits the entries that are returned by the server

Additionally, a list of requested attributes can be transmitted with the search request. Many LDAP SDKs will simply return all user attributes and no operational attributes if no requested attributes list is provided. In this case, request the attributes description and office and any others that are required.

LDAP-compliant servers enforce an access control scheme which might cause the server to not return certain attributes. Consult with the LDAP administrators to determine if the authentication state of the LDAP client connections have permission to access the attributes desired.

see also

  • LDAP: Using ldapsearch: this article refers to the ldapsearch command line tool, but the concepts are the same as for programmatic access.

Code Ref:

public boolean authenticate(String userid, String pass, String domain) {
        boolean retval = false;
        String searchFilter ="(&(objectClass=user)(" + LDAP_UID_ATTR + "=" + userid + "))";


        try {
            System.out.println("Start: getLDAPAttrs");
            NamingEnumeration answer =
                getLDAPAttrs(userid, pass, searchFilter, domain);
            String uid = "";

            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult)answer.next();

                Attributes attrs = sr.getAttributes();

                try {
                    uid = attrs.get(LDAP_UID_ATTR).toString();
                    System.out.println("uid: " + uid);
                    System.out.println(attrs.get("mail"));
                    uid = uid.substring(uid.indexOf(':') + 2);
                } catch (Exception err) {
//                    uid = "";
                    System.out.println(err.getMessage());
                    err.printStackTrace();
                }

                // verify userid
                if (userid.equalsIgnoreCase(uid)) {
                    retval = true;

                    break;
                }
            }
        } catch (NamingException ne) {
            System.out.println("In authenticateWithLDAP, LDAP Authentication NamingException : " +
                               ne.getMessage());
        } catch (Exception ex) {
            System.out.println("In authenticateWithLDAP, LDAP Authentication Exception : " +
                               ex.getMessage());
        }

        return retval;
        //        return retval;
    }

    private NamingEnumeration getLDAPAttrs(String userid, String pass,
                                           String searchFilter,
                                           String domain) throws NamingException,
                                                                 Exception {
        String host = getServerName();
        String port = getIP_Port();
        String dcPart1 = getDcPart1();
        String dcPart2 = getDcPart2();
//        String attrUserID = getLDAP_UID_ATTR();
//        String attrUserName = getLDAP_UNAME_ATTR();

        // set attribute names to obtain value of
        String[] returnedAtts = { "sAMAccountName", "cn","mail" };
        SearchControls searchCtls = new SearchControls();
        searchCtls.setReturningAttributes(returnedAtts);

        // specify the search scope
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // set search base
        String searchBase = "DC=" + dcPart1 + ",DC=" + dcPart2;

        // set ldap env values
        Hashtable environment = new Hashtable();
        environment.put(Context.INITIAL_CONTEXT_FACTORY,
                        "com.sun.jndi.ldap.LdapCtxFactory");
        environment.put(Context.PROVIDER_URL, "ldap://" + host + ":" + port);
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, userid + "@" + domain);
        environment.put(Context.SECURITY_CREDENTIALS, pass);

        // set ldap context
        DirContext ctxGC = new InitialDirContext(environment);

        // perform search to obtain values
        NamingEnumeration answer =
            ctxGC.search(searchBase, searchFilter, searchCtls);
        return answer;
    }

Email Validation

CHALLENGE DESCRIPTION:

You are given several strings that may/may not be valid emails. You should write a regular expression that determines if the email id is a valid email id or not. You may assume all characters are from the english language.

INPUT SAMPLE:

Your program should accept as its first argument a filename. This file will contain several text strings, one per line. Ignore all empty lines. E.g.

foo@bar.com
this is not an email id
admin#codeeval.com
good123@bad.com

OUTPUT SAMPLE:

Print out ‘true’ (all lowercase) if the string is a valid email. Else print out ‘false’ (all lowercase). E.g.

true
false
false
true

Solution:

import java.io.File;
import java.io.FileNotFoundException;

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String... args) throws Exception {
        Main main = new Main();
        main.startFileRead(args[0]);
    }

    public void startFileRead(String filePath) throws FileNotFoundException {
        File file = new File(filePath);


        if (file.exists()) {
            Scanner s = new Scanner(file);
            int n = 0;

            boolean tmp = false;
            while ((s.hasNextLine())) {
                tmp = EmailValidation(s.nextLine());
                System.out.println(tmp);
            }

        }
    }

    public boolean EmailValidation(String line) {
        Pattern pattern;
        Matcher matcher;
        String EMAIL_PATTERN =
            "^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$";
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(line);
        return matcher.matches();
    }
}

Swaps letters’ case in a sentence. All non-letter characters should remain the same.

INPUT SAMPLE:

Your program should accept as its first argument a path to a filename. Input example is the following

Hello world!
JavaScript language 1.8
A letter

OUTPUT SAMPLE:

hELLO WORLD!
jAVAsCRIPT LANGUAGE 1.8
a LETTER

Solution

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class Main {
    public Main() {
        super();
    }

    public static String reverseCase(String text) {
        char[] chars = text.toCharArray();
        for (int i = 0; i  0) {
                    System.out.println(Main.reverseCase(line));
                    ;
                }
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}

How to check if 2 Date Ranges Overlap in Java

Code to check if 2 date ranges overlap each other or not.


/**
* @return boolean true in case the date ranges overlap.
*/
boolean isOverLaped(Date start1,Date end1,Date start2,Date end2) throws NullPointerException{
    if ((start1.before(start2) && end1.after(start2)) || 
        (start1.before(end2) && end1.after(end2)) || 
        (start1.before(start2) && end1.after(end2))) {
        return true;
    } else {
        return false;
    }
}

Creating a re-organizable list of Items using Drag and Drop in Oracle ADF

Sometimes the requirement is to create a list of UI Items which can be rearranged using Drag and Drop in Oracle ADF, similar to the one in jQuery.

Oracle ADF Drag and Drop doesn’t provide the ability to identify, where the drag object is being dropped in the drag target. Thus we cannot know where to place the dropped element in the list.

here is the solution to the same:
Assumption:
–each element is same and is being iterated in a for loop over a list.
–Here dummy data is being used
Here is the below jsff segment:

<af:forEach var="v" varStatus="vi" begin="0" end="10">
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertAbove}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
    <h:panelGroup styleClass="" id="pg1232">
              <af:outputText value="#{vi.index}" id="ot1"><af:componentDragSource/></af:outputText>
    </h:panelGroup>
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertBelow}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
</af:forEach>

below is the Java Code for the managed bean:

needed imports:

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.datatransfer.DataFlavor;
import oracle.adf.view.rich.datatransfer.Transferable;
import oracle.adf.view.rich.dnd.DnDAction;
import oracle.adf.view.rich.event.DropEvent;

import org.apache.myfaces.trinidad.change.ChangeManager;
import org.apache.myfaces.trinidad.change.MoveChildComponentChange;
import org.apache.myfaces.trinidad.context.RequestContext;

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertBelow(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex + 1, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertAbove(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        //        System.out.println(dropTarget.getParent());
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

this code allows you place rearrange the list of items using drag and drop:

I1
I2
I3
I4
I5
I6
I7
I8

can be converted to by picking up I3 and placing it between I5 and I6 :

I1
I2
I4
I5
I3
I6
I7
I8

Parse String as Date in Java

Date and Time patterns used in java.text.SimpleDateFormat

Letter Date or Time Component Presentation Examples
G Era designator Text AD
y Year Year 1996; 96
Y Week year Year 2009; 09
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day name in week Text Tuesday; Tue
u Day number of week (1 = Monday, …, 7 = Sunday) Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
If ‘M’ is 3 or more, then the month is interpreted as text, else number.

Examples:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
    String dateInString = "7-Jun-2013";

    try {
 
    Date date = formatter.parse(dateInString);
    System.out.println(date);//Fri Jun 07 00:00:00 MYT 2013
        System.out.println(formatter.format(date));   
       } catch (ParseException e) {
              e.printStackTrace(); 
       }
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
    String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";        
 
    try {
 
        Date date = formatter.parse(dateInString);
        System.out.println(date);
        System.out.println(formatter.format(date));
 
    } catch (ParseException e) {
        e.printStackTrace();
    }
Fri Jun 07 12:10:56 MYT 2013
Friday, Jun 07, 2013 12:10:56 PM

Two player game program – e.g. TIC TAC TOE…

This is an abstract State class
public abstract class State {

// This method is abstract, the extending class has to give the implementation
// It will return a list of all the possible children from the current state.
public abstract List getChildren();
public abstract String getTurn();
public abstract void setTurn(String turn);

// Find out who is the winner from the current state.
public abstract String getWinner();

// Check if the game has been finished or not.
public abstract boolean isGameOver();

// I have given the implementation specifically for TIC-TAC-TOE.
// You can override this functionality in the extending class according to your game requirements.
//
// This function will give the score of the current state.
// Then you can compare it with its siblings to check which state will be better to move to..
//
public int minimax()
{

if(!getWinner().equals(""))
{
if("X".equalsIgnoreCase(getWinner()))
{
return 1;
}
if("O".equalsIgnoreCase(getWinner()))
{
return -1;
}
if("draw".equalsIgnoreCase(getWinner()))
{
return 0;
}
}
List children = getChildren();
if(getTurn().equals("X"))
{
int maxScore = -100;
for(State child : children)
{
int childScore = child.minimax();
if(childScore > maxScore)
{
maxScore = childScore;
}
}
return maxScore;
}
else
{
int minScore = 100;
for(State child : children)
{
int childScore = child.minimax();
if(childScore < minScore)
{
minScore = childScore;
}
}
return minScore;
}

}
}

Extend the above State class and give some implementations…as follows:
Lets assume the class to be TttState…
We’ll override the abstract methods of the parent class State..

Give a member variable that’ll hold the current state of your game…In my case, I have taken it as array..

// This variable is going to hold the current state of your game.
// It can be any depending on your game requirements...
private String state[][] = null ;

Give a copy constructor

public TttState(State x)
{
TttState tState = (TttState)x;
state = new String[3][3];
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
this.state[i][j]=tState.state[i][j];
}
}
this.turn = x.getTurn();
}

Give a default constructor

public TttState() {
state = new String[3][3];
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
this.state[i][j]="";
}
}
this.turn = "X";
}

Give a toString implementation, so that you can print the current state

public String toString()
{
StringBuilder sb = new StringBuilder("");
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
sb.append("-");
}
else
{
sb.append(state[i][j]);
}
sb.append("t");
}
sb.append("n");
}
return sb.toString();
}

Override the method getWinner() as follows

public String getWinner()
{
// ROW CHECK BEGINS
if(state[0][0].equalsIgnoreCase("X") && state[0][1].equalsIgnoreCase("X") && state[0][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[0][1].equalsIgnoreCase("O") && state[0][2].equalsIgnoreCase("O"))
{
return "O";
}
if(state[1][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[1][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O"))
{
return "O";
}
if(state[2][0].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[2][0].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}

// COLUMN CHECK BEGINS
if(state[0][0].equalsIgnoreCase("X") && state[1][0].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[1][0].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
{
return "O";
}
if(state[0][1].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][1].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][1].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][1].equalsIgnoreCase("O"))
{
return "O";
}
if(state[0][2].equalsIgnoreCase("X") && state[1][2].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][2].equalsIgnoreCase("O") && state[1][2].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}
// DIAGNONAL CHECKS
if(state[0][0].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][2].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][0].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][2].equalsIgnoreCase("O"))
{
return "O";
}

if(state[0][2].equalsIgnoreCase("X") && state[1][1].equalsIgnoreCase("X") && state[2][0].equalsIgnoreCase("X"))
{
return "X";
}
if(state[0][2].equalsIgnoreCase("O") && state[1][1].equalsIgnoreCase("O") && state[2][0].equalsIgnoreCase("O"))
{
return "O";
}
int nonBlank = 0;
for(int i=0;i<=2;i++)
{
for(int j=0;j<=2;j++)
{
if(!state[i][j].equals(""))
{
nonBlank++;
}
}
}
if(nonBlank==9)
{
return "draw";
}

return "";
}

Override the method isGameOver()

public boolean isGameOver()
{
if(!getWinner().equals("") && !getWinner().equals("draw"))
{
return true;
}
else
{
return false;
}
}

Override the method getChildren()

@Override
public List getChildren() {
List children = new ArrayList();
if(turn.equals("X"))
{
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
TttState child = new TttState(this);
child.state[i][j]="X";
String newTurn = "O";
child.setTurn(newTurn);
children.add(child);
}
}
}
}
else
{
for(int i=0;i<=2; i++)
{
for(int j=0; j<=2;j++)
{
if(state[i][j].equals(""))
{
TttState child = new TttState(this);
child.state[i][j]="O";
String newTurn = "X";
child.setTurn(newTurn);
children.add(child);
}
}
}
}
return children;
}

Override getTurn and setTurn

public String getTurn() {
return turn;
}

public void setTurn(String turn) {
this.turn = turn;
}

Your main program will look something like this:

public static void main(String args[])
{
TttState x = new TttState();
System.out.println("WINNER : " + x.getWinner());
x.setTurn("X");
Scanner sc = new Scanner(System.in);
while(!x.isGameOver())
{
String xIndex = sc.nextLine();
String yIndex = sc.nextLine();
int xint = Integer.parseInt(xIndex);
int yint = Integer.parseInt(yIndex);
x.getState()[xint][yint]="X";
x.setTurn("O");
int minScore = 100;
List children = x.getChildren();
TttState bestMove = new TttState(x);
for(State child : children)
{
int childScore = child.minimax();
// We are using < because we are always evaluating
// the best move from the options that O player has....
if(childScore < minScore)
{
minScore = childScore;
bestMove = (TttState)child;
bestMove.setTurn("X");
}
}
System.out.print(bestMove);
x = bestMove;
}
System.out.println("GAME OVER...");

}

Programmatically Populate View Objects Based on ArrayList of custom Bean Class In Oracle ADF

Lets say you have a Custom Bean Class EmpData defined as:

EmpData

And you wish to use the same as a View Object, Then below is the method for the same:

First create a Proxy View Object Class:
ProxyDataSourceObject

Now Create a View Object where it is populated programmatically:
Programmatic_VO

Programmatic_VO_attribs

Programmatic_VO_Java

EmpDataCustomVO

Now Edit the View Object Impl Class:

EmpDataCustomVOImpl

Now you can easily use the View Objects as a normal View Object to be used in View Controller.

Cons: The getDataFromService method will be called again and again whenever the View Object is needed. So try to keep the source separate and apply some tuning logic to the same in order to improve performance of system.

Original Referrence Source