Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 06-29-2009, 08:12 PM
jon80's Avatar
Senior Member
 
Join Date: Feb 2008
Posts: 195
Rep Power: 2
jon80 is on a distinguished road
Default [newbie] java.lang.NullPointerException
What kind of file does the following code expect? Why is it breaking?




Code:
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;
import javax.swing.*;

/**
    This program demonstrates access to a hierarchical database through LDAP
*/
public class LDAPTest
{
    public static void main(String[] args)
    {
       JFrame frame = new LDAPFrame();
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setVisible(true);
    }
}

 /**
    The frame that holds the data panel and the navigation buttons.
 */
 class LDAPFrame extends JFrame
 {
    public LDAPFrame()
    {
       setTitle("LDAPTest");
       setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

       JPanel northPanel = new JPanel();
       northPanel.setLayout(new java.awt.GridLayout(1, 2, 3, 1));
       northPanel.add(new JLabel("uid", SwingConstants.RIGHT));
       uidField = new JTextField();
       northPanel.add(uidField);
       add(northPanel, BorderLayout.NORTH);

       JPanel buttonPanel = new JPanel();
       add(buttonPanel, BorderLayout.SOUTH);

       findButton = new JButton("Find");
       findButton.addActionListener(new
          ActionListener()
          {
             public void actionPerformed(ActionEvent event)
             {
                findEntry();
             }
          });
       buttonPanel.add(findButton);

       saveButton = new JButton("Save");
       saveButton.addActionListener(new
           ActionListener()
           {
              public void actionPerformed(ActionEvent event)
              {
                 saveEntry();
              }
           });
        buttonPanel.add(saveButton);

        deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new
           ActionListener()
           {
              public void actionPerformed(ActionEvent event)
              {
                 deleteEntry();
              }
           });
        buttonPanel.add(deleteButton);

        addWindowListener(new
           WindowAdapter()
           {
              public void windowClosing(WindowEvent event)
              {
                 try
                 {
                    if (context != null) context.close();
                 }
                 catch (NamingException e)
                 {
                    e.printStackTrace();
                 }
              }
          });
     }

     /**
        Finds the entry for the uid in the text field.
     */
     public void findEntry()
     {
        try
        {
          if (scrollPane != null) remove(scrollPane);
          String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com";
          if (context == null) context = getContext();
          attrs = context.getAttributes(dn);
          dataPanel = new DataPanel(attrs);
          scrollPane = new JScrollPane(dataPanel);
          add(scrollPane, BorderLayout.CENTER);
          validate();
          uid = uidField.getText();
       }
       catch (NamingException e)
       {
          JOptionPane.showMessageDialog(this, e);
       }
       catch (IOException e)
       {
          JOptionPane.showMessageDialog(this, e);
       }
    }

    /**
       Saves the changes that the user made.
    */
    public void saveEntry()
    {
       try
       {
          if (dataPanel == null) return;
          if (context == null) context = getContext();
          if (uidField.getText().equals(uid)) // update existing entry
          {
             String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com";
             Attributes editedAttrs = dataPanel.getEditedAttributes();
             NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
             while (attrEnum.hasMore())
             {
                Attribute attr = attrEnum.next();
                String id = attr.getID();
                Object value = attr.get();
                Attribute editedAttr = editedAttrs.get(id);
                if (editedAttr != null && !attr.get().equals(editedAttr.get()))
                   context.modifyAttributes(dn, DirContext.REPLACE_ATTRIBUTE,
                      new BasicAttributes(id, editedAttr.get()));
             }
          }
          else // create new entry
          {
             String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com";
             attrs = dataPanel.getEditedAttributes();
             Attribute objclass = new BasicAttribute("objectClass");
             objclass.add("uidObject");
             objclass.add("person");
             attrs.put(objclass);
             attrs.put("uid", uidField.getText());
             context.createSubcontext(dn, attrs);
          }

          findEntry();
       }
       catch (NamingException e)
       {
          JOptionPane.showMessageDialog(LDAPFrame.this, e);
          e.printStackTrace();
       }
       catch (IOException e)
       {
          JOptionPane.showMessageDialog(LDAPFrame.this, e);
          e.printStackTrace();
       }
    }

    /**
       Deletes the entry for the uid in the text field.
    */
    public void deleteEntry()
    {
       try
       {
          String dn = "uid=" + uidField.getText() + ",ou=people,dc=mycompany,dc=com";
          if (context == null) context = getContext();
          context.destroySubcontext(dn);
          uidField.setText("");
          remove(scrollPane);
          scrollPane = null;
          repaint();
       }
       catch (NamingException e)
       {
          JOptionPane.showMessageDialog(LDAPFrame.this, e);
          e.printStackTrace();
       }
       catch (IOException e)
       {
          JOptionPane.showMessageDialog(LDAPFrame.this, e);
          e.printStackTrace();
       }
    }

    /**
       Gets a context from the properties specified in the file ldapserver.properties
       @return the directory context
    */
    public static DirContext getContext()
       throws NamingException, IOException
    {
       Properties props = new Properties();
       FileInputStream in = new FileInputStream("ldapserver.properties");
       props.load(in);
       in.close();

       String url = props.getProperty("ldap.url");
       String username = props.getProperty("ldap.username");
       String password = props.getProperty("ldap.password");

       Hashtable<String, String> env = new Hashtable<String, String>();
       env.put(Context.SECURITY_PRINCIPAL, username);
       env.put(Context.SECURITY_CREDENTIALS, password);
       DirContext initial = new InitialDirContext(env);
       DirContext context = (DirContext) initial.lookup(url);

       return context;
    }

    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 200;

    private JButton findButton;
    private JButton saveButton;
    private JButton deleteButton;

    private JTextField uidField;
    private DataPanel dataPanel;
    private Component scrollPane;

    private DirContext context;
    private String uid;
    private Attributes attrs;
 }

 /**
    This panel displays the contents of a result set.
 */
 class DataPanel extends JPanel
 {
    /**
       Constructs the data panel.
       @param attributes the attributes of the given entry
    */
    public DataPanel(Attributes attrs) throws NamingException
    {
       setLayout(new java.awt.GridLayout(0, 2, 3, 1));

       NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
       while (attrEnum.hasMore())
       {
          Attribute attr = attrEnum.next();
          String id = attr.getID();

          NamingEnumeration<?> valueEnum = attr.getAll();
          while (valueEnum.hasMore())
          {
             Object value = valueEnum.next();
             if (id.equals("userPassword"))
                value = new String((byte[]) value);

             JLabel idLabel = new JLabel(id, SwingConstants.RIGHT);
             JTextField valueField = new JTextField("" + value);
             if (id.equals("objectClass"))
                valueField.setEditable(false);
             if (!id.equals("uid"))
             {
                add(idLabel);
                add(valueField);
             }
          }
       }
    }

    public Attributes getEditedAttributes()
    {
       Attributes attrs = new BasicAttributes();
       for (int i = 0; i < getComponentCount(); i += 2)
       {
          JLabel idLabel = (JLabel) getComponent(i);
          JTextField valueField = (JTextField) getComponent(i + 1);
          String id = idLabel.getText();
          String value = valueField.getText();
          if (id.equals("userPassword"))
             attrs.put("userPassword", value.getBytes());
          else if (!id.equals("") && !id.equals("objectClass"))
             attrs.put(id, value);
       }
       return attrs;
    }
}
Error
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:394)
at LDAPFrame.getContext(LDAPTest.java:215)
at LDAPFrame.findEntry(LDAPTest.java:102)
at LDAPFrame$1.actionPerformed(LDAPTest.java:49)
at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:19
95)
at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.jav
a:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel
.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:242
)
at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonL
istener.java:236)
at java.awt.Component.processMouseEvent(Component.jav a:6216)
at javax.swing.JComponent.processMouseEvent(JComponen t.java:3265)
at java.awt.Component.processEvent(Component.java:598 1)
at java.awt.Container.processEvent(Container.java:204 1)
at java.awt.Component.dispatchEventImpl(Component.jav a:4583)
at java.awt.Container.dispatchEventImpl(Container.jav a:2099)
at java.awt.Component.dispatchEvent(Component.java:44 13)
at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4556
)
at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4220)

at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4150)
at java.awt.Container.dispatchEventImpl(Container.jav a:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475 )
at java.awt.Component.dispatchEvent(Component.java:44 13)
at java.awt.EventQueue.dispatchEvent(EventQueue.java: 599)
at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThre
ad.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.
java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThre
ad.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:169)

at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:161)

at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:122)

Code:
ldapserver.properties (originally named sample.ldif; then renamed it)
# Define top-level entry
dn: dc=mycompany,dc=com
objectClass: dcObject
objectClass: organization
dc: mycompany
o: Core Java Team
# Define an entry to contain people
# searches for users are based on this entry
dn: ou=people,dc=mycompany,dc=com
objectClass: organizationalUnit
ou: people
# Define a user entry for John Q. Public
dn: uid=jqpublic,ou=people,dc=mycompany,dc=com
objectClass: person
objectClass: uidObject
uid: jqpublic
sn: Public
cn: John Q. Public
telephoneNumber: +1 408 555 0017
userPassword: wombat

# Define a user entry for Jane Doe
dn: uid=jdoe,ou=people,dc=mycompany,dc=com
objectClass: person
objectClass: uidObject
uid: jdoe
sn: Doe
cn: Jane Doe
telephoneNumber: +1 408 555 0029
userPassword: heffalump

# Define an entry to contain LDAP groups
# searches for roles are based on this entry
dn: ou=groups,dc=mycompany,dc=com
objectClass: organizationalUnit
ou: groups

# Define an entry for the "techstaff" group
dn: cn=techstaff,ou=groups,dc=mycompany,dc=com
objectClass: groupOfUniqueNames
cn: techstaff
uniqueMember: uid=jdoe,ou=people,dc=mycompany,dc=com

# Define an entry for the "staff" group
dn: cn=staff,ou=groups,dc=mycompany,dc=com
objectClass: groupOfUniqueNames
cn: staff
uniqueMember: uid=jqpublic,ou=people,dc=mycompany,dc=com
uniqueMember: uid=jdoe,ou=people,dc=mycompany,dc=com

Last edited by jon80; 06-29-2009 at 08:15 PM.
Bookmark Post in Technorati
Reply With Quote
  #2 (permalink)  
Old 06-29-2009, 08:19 PM
makpandian's Avatar
Senior Member
 
Join Date: Dec 2008
Location: Chennai
Posts: 253
Rep Power: 2
makpandian is on a distinguished road
Default
i am not sure,But i think,You might have passed null value into the HashTable.
__________________
Mak
(Living @ Virtual World)
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 06-30-2009, 05:37 AM
Eranga's Avatar
Moderator
 
Join Date: Jul 2007
Location: Colombo, Sri Lanka
Posts: 7,256
Rep Power: 11
Eranga has a spectacular aura aboutEranga has a spectacular aura about
Send a message via Yahoo to Eranga
Default
Ya, somewhere cause with a null value. Cannot you debug near the hash table insertion? I think it's the easiest way to find the solution.
__________________
Use an appropriate Subject. "Help, urgent!" isn't one.
Someone helped you? their helpful post.
Help:Forums FAQ|How To Ask Questions The Smart WayResources:The Java Tutorials|Glossary for Java|NetBeans IDE|Sun DownloadsWeb:WritOnceTips:Is your IDE the best?|Which Application Server?
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
[newbie] java.lang.NullPointerException jon80 New To Java 5 09-25-2009 09:43 AM
[SOLVED] [newbie] java.lang.NullPointerException jon80 New To Java 5 05-07-2009 05:19 PM
java.lang.NullPointerException vasavi.singh New To Java 1 02-27-2009 01:36 PM
java.lang.NullPointerException stevemcc AWT / Swing 2 02-08-2008 10:01 AM
java.lang.NullPointerException Felissa Advanced Java 1 07-05-2007 07:02 AM


All times are GMT +2. The time now is 12:59 PM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org