GIDForums  

Go Back   GIDForums > Computer Programming Forums > Java Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 29-Dec-2006, 12:50
valley1girl valley1girl is offline
New Member
 
Join Date: Dec 2006
Posts: 2
valley1girl is on a distinguished road

Exception in thread "main" java.lang.NullPointerException


Hi I was wondering if anyone could see why i'm getting the Error

Code:
Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Unknown Source) at java.awt.Container.add(Unknown Source) at game.Interface.getJContentPane(Interface.java:99) at game.Interface.<init>(Interface.java:56) at game.Interface.main(Interface.java:37)

Heres the code thanks:

JAVA Code:
package game;

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

public class Interface extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JToolBar jToolBar = null;
	private JButton jNewGameButton = null;
	private JButton jPauseGameButton = null;
	private JButton jResumeGameButton = null;
	private JButton jExitButton = null;
	
	private ConnectFour game;
	private GameBoard panel;
	private boolean finished;
	private int rows;
	private int columns;
	private int cellWidth;
	private int cellHeight;
	private int panelWidth;
	private int panelHeight;
	private boolean animate = false;
	private int position;
	private int animateColumn;
	private int animateRow;
	public static final char p1 = 'x';
	public static final char p2 = 'y';
	public static final int animateStepSize = 12;
	public static final long animateTimeDelay = 22;

	public static void main(String[] args) {
				Interface gui = new Interface();
				gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				gui.setVisible(true);
	}


	public Interface() {
		
		rows = 5;
		columns = 5;
		cellWidth = 30;
		cellHeight = 30;
		panelWidth = 400;
		panelHeight = 400;
		finished = false;
		game = new ConnectFour(rows, columns, p1, p2);
		panel = new GameBoard(game);
		addMouseListener(new ClickListener());
		
		this.setContentPane(getJContentPane());
		this.setSize(new Dimension(484,242));
		this.setTitle("Connect Four");
		
		JToolBar jToolBar = new JToolBar();
		jToolBar.setSize(new Dimension(477, 34));
		jToolBar.setFloatable(false);
		jToolBar.add(jNewGameButton);
		jToolBar.add(jPauseGameButton);
		jToolBar.add(jResumeGameButton);
		jToolBar.add(jExitButton);
		
		JButton jNewGameButton = new JButton();
		jNewGameButton.setText("New Game");
		jNewGameButton.setToolTipText("Click here to start a new game");
		jNewGameButton.setBackground(new Color(255, 221, 238));
		jNewGameButton.addActionListener(new NewGameListener());
		
		JButton jPauseGameButton = new JButton();
		jPauseGameButton.setText("Pause Game");
		jPauseGameButton.setToolTipText("Click here to pause game");
		jPauseGameButton.setBackground(new Color(255, 221, 238));
		jPauseGameButton.addActionListener(new PauseGameListener());
		
		JButton jResumeGameButton = new JButton();
		jResumeGameButton.setText("Resume Game");
		jResumeGameButton.setToolTipText("Click here to resume paused game");
		jResumeGameButton.setBackground(new Color(255, 221, 238));
		jResumeGameButton.addActionListener(new ResumeGameListener());
		
		JButton jExitButton = new JButton();
		jExitButton.setText("Exit");
		jExitButton.setToolTipText("Click here to close program");
		jExitButton.setBackground(new Color(255, 221, 238));
		jExitButton.addActionListener(new ExitListener());
	}

	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.setForeground(new Color(65, 65, 68));
			jContentPane.setBackground(new Color(238, 184, 238));
			jContentPane.add(jToolBar,BorderLayout.NORTH);
		}
		return jContentPane;
	}

	private class ClickListener extends MouseAdapter{
		public void mouseReleased(MouseEvent e){
			[i]some code[/i]
                         }
             }

	private class NewGameListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			[i]some code[/i]
                         }
             }


	private class PauseGameListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			[i]some code[/i]
		}
	}

	private class ResumeGameListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			[i]some code[/i]
		}
	}

	private class ExitListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			[i]some code[/i]
		}
	}

	private class GameBoard extends JPanel{
		private static final long serialVersionUID = 1L;
		private ConnectFour myGame;
		private int fontSize;
		public GameBoard(ConnectFour game){
			[i]some code[/i];
		}

		public void resetGame(ConnectFour newGame){
			[i]some code[/i]
		}

		protected void paintComponent(Graphics g){
			[i]some code[/i]
	             }
             }

}
Last edited by LuciWiz : 29-Dec-2006 at 15:15. Reason: Please insert your Java code between [java] & [/java] tags
  #2  
Old 29-Dec-2006, 22:26
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,141
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


Like, oh my god!, let's like totally do a stack trace of that 'Exception'...

(from the bottom->up)
line 37 is this statement, in main():
JAVA Code:
     Interface gui = new Interface();
Well that looks ok, nothing strange, just creating a new Interface object, so move to the next line (up the stack)...


line 56 is this statement [note the <init> implies "during construction" (or "in the constructor")]
JAVA Code:
     this.setContentPane(getJContentPane());
this still looks ok, but there is a function call as the argument, could that be causing trouble? Lets follow the stack (up another line)...


to line 99:
JAVA Code:
     jContentPane.add(jToolBar,BorderLayout.NORTH);
Whoa!, looky here, we are IN that function call [from line 56], and there is something about this statement causing the add() call to bomb (the 'null pointer' exception), because the last two dump lines have 'unknown source'.

So, what is it about this statement [line 99] that could possibly be null?

I'll stop here to let you ponder it, but if you get stuck, post another reply.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #3  
Old 30-Dec-2006, 15:23
valley1girl valley1girl is offline
New Member
 
Join Date: Dec 2006
Posts: 2
valley1girl is on a distinguished road

Re: Exception in thread "main" java.lang.NullPointerException


Hi thanks for your help but I still don't understand how it is null. I'm kinda new to java and debugging so if im appearing naiive, sorry, but is there anything else that you can tell me as a hint.

thanks again,
Kirsty
  #4  
Old 30-Dec-2006, 21:14
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,141
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


Another hint: follow your constructor code...

What is the value of 'jToolBar' when it is used from the call point at line 56?
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #5  
Old 17-Jun-2009, 08:52
idrismca idrismca is offline
New Member
 
Join Date: Jun 2009
Posts: 5
idrismca is on a distinguished road

Re: Exception in thread "main" java.lang.NullPointerException


i m facing similar problems any help???
  #6  
Old 17-Jun-2009, 11:05
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,141
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


Follow the stack trace from bottom->up.

I can't refer to exact lines, because you didn't post any code -- nor the dump, but the dump does provide the <file.java>:<line#> reference that should be easy to follow.

Java is typically pretty good at pinpointing the problem, but it's not always obvious, so if you still have trouble, post another reply with more details. (i.e. the dump and source)

Follow the guidelines about code posting, please, so that it will be formatted. (see the first two posts)
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #7  
Old 17-Jun-2009, 12:00
idrismca idrismca is offline
New Member
 
Join Date: Jun 2009
Posts: 5
idrismca is on a distinguished road

Re: Exception in thread "main" java.lang.NullPointerException


oh yes here's the code and the error


code....
JAVA Code:
package com.chanderasset.ui.taxlot.forms;

import com.chanderasset.business.Context;
import com.chanderasset.business.ApplicationBeanFactory;
import com.chanderasset.business.model.portfolio.controller.OperationController;
import com.chanderasset.business.model.portfolio.controller.PortfolioController;
import com.chanderasset.business.model.portfolio.controller.TaxLotController;
import com.chanderasset.business.model.portfolio.controller.OperationArgs;
import com.chanderasset.business.model.portfolio.beans.chanderPortfolio;
import com.chanderasset.business.model.portfolio.beans.chanderOperation;
import com.chanderasset.business.model.portfolio.beans.chanderTransaction;
import com.chanderasset.business.model.portfolio.beans.OpenPosition;
import com.chanderasset.ui.util.SwingWorker;
import com.chanderasset.ui.model.OperationTable;
import com.chanderasset.ui.model.CheckBoxTable;
import com.chanderasset.business.model.fund.beans.chanderProductRedemptionOperation;
import com.chanderasset.business.model.fund.beans.chanderProductOperation;
import com.chanderasset.business.model.fund.controller.SecurityController;


import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableCellRenderer;


import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;

import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.util.List;


/**
 * com.chanderasset.ui.taxlot.forms
 *
 * @author chander
 * @version $Id: TaxLotToolUI.java,v 1.9 2009/06/09 15:39:21 ibaxamusa Exp $
 */
public class TaxLotToolUI {
    // logging
    private static final Logger log = LogManager.getLogger(TaxLotToolUI.class);

    // gui globals
    private JPanel mainPanel;
    private JTextField _username;
    private JPasswordField _password;
    private JButton _loginButton;
    private JPanel _loginPanel;
    private JPanel _portfolioPanel;
    private JComboBox _portfolioList;
    private JButton _retrieveOperationsButton;
    private JPanel PortfolioContainer;
    private JSeparator _loginSeperator;
    private JPanel _operationPanel;
    private JTextArea _status;
    private JTable _operationTable;
    private JScrollPane _operationContainer;
    private JScrollPane _transactionContainer;
    private JButton _updateButton;
    private JLabel _Transaction_Title;
    private JLabel _Operations_Title;
    private JTextField _operationId;
    private JButton _retriveTransactionsButton;
    private JPanel popupPanel;
    private JTable table;

    protected int noOfRows;
    protected Object[][] data;
    protected long operationId;
    protected String operationDate;
    protected String operationName;


    // app globals
    protected Context context;
    protected TaxLotController taxlotController = null;
    protected PortfolioController portfolioController = null;
    protected OperationController operationController = null;
    protected chanderPortfolio _currentPortfolio = null;
    protected Collection<chanderOperation> _currentOperations = null;
    protected Map<String,chanderPortfolio> portfolioMap = null;
    protected chanderProductRedemptionOperation productRedemptionOperation = null;
    protected SecurityController securityController =null;
    protected Map<Long,chanderOperation> _operationMap = new HashMap<Long,chanderOperation>();
    protected Collection<OpenPosition> openpositions=null;
    protected Collection<chanderTransaction> chanderTransaction=null;



    // constants
    private static final String ACTION_LOGIN = "ACTION_LOGIN";
    private static final String ACTION_RETRIEVE_OPERATIONS = "ACTION_RETRIEVE_OPERATIONS";
    private static final String ACTION_UPDATE = "ACTION_UPDATE";
    private static final String ACTION_RETRIEVE_TRANSACTIONS = "ACTION_RETRIEVE_TRANSACTIONS";




    /**
     * constructor
     */
    public TaxLotToolUI() {
        // add shutdown hook
        java.lang.Runtime.getRuntime().addShutdownHook(new TaxLotShutdownHook());

       //i logToUI("");


        // TODO: remove these defaults
       // _username.setText("");
      //  _password.setText("");


          _password.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        benportLogin(_username.getText(), new String(_password.getPassword()));
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );

        _loginButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_LOGIN.equals(e.getActionCommand())) {

                                SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        benportLogin(_username.getText(), new String(_password.getPassword()));
                                        return null;
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );

        _loginButton.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        benportLogin(_username.getText(), new String(_password.getPassword()));
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );

        _retrieveOperationsButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_RETRIEVE_OPERATIONS.equals(e.getActionCommand()) && _portfolioList.getSelectedIndex()>0) {

                                _currentPortfolio =  portfolioMap.get( _portfolioList.getSelectedItem() );
                                _operationContainer.setVisible(false);
                                _Operations_Title.setVisible(false);
                                _transactionContainer.setVisible(false);
                                _Transaction_Title.setVisible(false);
                                _updateButton.setVisible(false);
                                SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        return (Object) loadPortfolioOperations( _currentPortfolio );
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );

         _retriveTransactionsButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_RETRIEVE_TRANSACTIONS.equals(e.getActionCommand())) {
                                  _operationContainer.setVisible(false);
                                  _Operations_Title.setVisible(false);
                                  _transactionContainer.setVisible(true);
                                  _updateButton.setVisible(true);
                                 SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                       showTransactionsforId();
                                       return null;
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );

         _retriveTransactionsButton.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                            _operationContainer.setVisible(false);
                            _Operations_Title.setVisible(false);
                            _transactionContainer.setVisible(true);
                            _updateButton.setVisible(true);
                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        showTransactionsforId();
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );
        _operationId.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                            _operationContainer.setVisible(false);
                            _Operations_Title.setVisible(false);
                            _transactionContainer.setVisible(true);
                            _updateButton.setVisible(true);
                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                    showTransactionsforId();
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );
          _updateButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_UPDATE.equals(e.getActionCommand()) ) {

                               _transactionContainer.setVisible(false);
                               _Transaction_Title.setVisible(false);
                               _updateButton.setVisible(false);
                                
                                SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {

                                        updateTaxLots(table);
                                        return null;
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );
        

        _operationContainer.addMouseListener(new MouseAdapter() {
               });



     
    }

    /**
     * benportLogin
     */
    protected void benportLogin(String username, String password) {
        // log in to benport
        logToUI("Logging in to benport...");
        try {
            context = (Context) ApplicationBeanFactory.getInstance().getBean("context");
        } catch (Exception e) {
        }

        try {
            context.setUserName(_username.getText());
            context.setPassWord(new String(_password.getPassword()) );
            context.login();


            // get controllers
            portfolioController = (PortfolioController) ApplicationBeanFactory.getInstance().getBean("portfolioController");
            taxlotController = (TaxLotController) ApplicationBeanFactory.getInstance().getBean("taxlotController");
            operationController = (OperationController) ApplicationBeanFactory.getInstance().getBean("operationController");
            securityController=(SecurityController) ApplicationBeanFactory.getInstance().getBean("securityController");




        } catch (Exception e) {
            log.error("Could not log in! "+e);
            logToUI("ERROR: Could not log in to benport!");
        }

        // post login
        if (authenticated()) {
            _loginPanel.setVisible(false);
            _portfolioPanel.setVisible(true);
            loadPortfolios();
        }


       logToUI("Ready.");
    }


    /**
     * loadPortfolios
     */
    private void loadPortfolios() {

        logToUI("Loading portfolio list...");

        try {
            Collection<chanderPortfolio> portfolios = portfolioController.getPortfolios("Real Time");
            portfolioMap = new HashMap<String,chanderPortfolio>();
            for (chanderPortfolio portfolio : portfolios) {
                _portfolioList.addItem( portfolio.getShortName() );
                portfolioMap.put( portfolio.getShortName(), portfolio );



            }
        } catch (Exception e) {
            //
        }

        if (null != portfolioMap && !portfolioMap.isEmpty()) {
            _portfolioList.setEnabled(true);
            _retrieveOperationsButton.setEnabled(true);
            if(_portfolioList.getItemAt(0).equals("Please choose a Portfolio")){}else{
            _portfolioList.insertItemAt("Please choose a Portfolio",0);// blank
            log.info("porTTFOLIO");                                                   }
            _portfolioList.setSelectedIndex(0);
           _operationId.setEnabled(true);
            _operationId.setEditable(true);
            _retriveTransactionsButton.setEnabled(true);
            logToUI("Portfolio list retrieved.");
        }
    }

    /**
     * loadOperations
     * @param portfolio The portfolio object
     * @return list of operations
     */
    private Collection<chanderOperation> loadPortfolioOperations(chanderPortfolio portfolio) {
        log.info("Loading portfolio operations for "+portfolio.getShortName());
        Collection<chanderOperation>  operations = null;

        OperationArgs opQuery = new OperationArgs();
        opQuery.setPortfolioId( portfolio.getExternalPortfolioId() );
        opQuery.justEstimated();
        opQuery.justRedemption();

        logToUI("Loading operations for "+portfolio.getShortName()+"...");
        try {
            operations = operationController.getOperations(opQuery);
        } catch (Exception e) {
            log.error("Could not load operations: "+e,e);
        }


        if (null != operations) {

            for (chanderOperation operation : operations) {
                _operationMap.put( operation.getExternalOperationId(), operation);
            }

            logToUI("Found "+operations.size()+" operations in "+portfolio.getShortName()+".");

            _operationContainer.setEnabled(true);
            JTable _operationList = new JTable(new OperationTable(operations));

            setupTable(_operationList);

            _operationContainer.setViewportView(_operationList);
            _operationContainer.updateUI();
        }

            _operationContainer.setVisible(true);
            _Operations_Title.setVisible(true);
            _Operations_Title.setText("Operations for "+portfolio.getShortName());
            _Operations_Title.updateUI();

        return operations;
    }


    /**
     * setupColumnWidths
     * this is ugly but a WIP.
     */
    private void setupTable(final JTable table) {
        table.getColumnModel().getColumn(0).setPreferredWidth(100);
        table.getColumnModel().getColumn(1).setPreferredWidth(350);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);
        table.getColumnModel().getColumn(3).setPreferredWidth(250);
        table.getColumnModel().getColumn(4).setPreferredWidth(100);
       
        TableColumn column = table.getColumnModel().getColumn(4);
        table.getColumnModel().removeColumn(column);
        //CheckBoxTableRenderer renderer = new CheckBoxTableRenderer();
		//renderer.setHorizontalAlignment(SwingConstants.RIGHT);
		//table.getColumnModel().getColumn(1).setCellRenderer(renderer);
        table.setAutoCreateRowSorter(true);
        
        table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {

					int maxRows;
					int[] selRows;
					Object value;

					_transactionContainer.setVisible(true);
                    _updateButton.setVisible(true);
                    selRows = table.getSelectedRows();
					TableModel tm;
					tm = table.getModel();
					if (selRows.length > 0) {
						for (int i= 0; i < 4 ; i++) {
						  // get Table data
                            value=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),i);
                        }
					}

					value=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),4);
                    String s=value.toString();
					operationId = Long.parseLong(s.trim());
                    operationName=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),1).toString();
                    operationDate=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),2).toString();
                    log.info("Loading positions for operation"+operationId);
					showallPositions(_operationMap.get(operationId));
				}
			}
     	});
    }

    private void createUIComponents() {
        // TODO: place custom component creation code here
    }


    private void showallPositions(chanderOperation chanderOperation) {

		log.info("Showing all positions for operation "+chanderOperation.getExternalOperationId());
        chanderProductRedemptionOperation chanderproductRedemptionOperation=(chanderProductRedemptionOperation) chanderOperation;
        chanderTransaction=chanderproductRedemptionOperation.getOpenTransactions();
        log.info("DATEI "+chanderOperation.getAsOfDate());
        Date _asOfDate, _daybefore;
        Calendar calendar;

            _asOfDate = chanderOperation.getAsOfDate();
            calendar = Calendar.getInstance();
            calendar.setTime(_asOfDate);
            calendar.add(Calendar.DATE, -1);
            _daybefore = calendar.getTime();

        openpositions = taxlotController.getAvailableTaxLots(chanderproductRedemptionOperation.getExternalProductId(),chanderOperation.getExternalPortfolioId(),_daybefore) ;
		log.info("FOUND "+(null != openpositions ? openpositions.size() : 0) + " OPEN POSITIONS");

         try {
             _transactionContainer.setVisible(true);
             _Transaction_Title.setVisible(true);
             _Transaction_Title.setText("Tax Lots for "+operationName +" as of "+operationDate);
             _Transaction_Title.updateUI();

             int rownum=0;
             int colnum=0;
             noOfRows=openpositions.size();
			 log.info("openpositions.size() ="+noOfRows);


             data = new Object[noOfRows][4];

			 // loop through all available transactions
			 Map taxlotMap = new HashMap();
			 Map taxlotStatus = new HashMap();
			 for (OpenPosition openposition : openpositions) {
				taxlotStatus.put( openposition.getExternalOpenTransactionId(), Boolean.FALSE );
				taxlotMap.put( openposition.getExternalOpenTransactionId(), openposition );
			 }
			 log.info("taxlotStatus.size="+taxlotStatus.size());

			 // toggle flag on transactions currently linked to the operation
			 for (chanderTransaction atran : chanderTransaction) {
				if (taxlotStatus.containsKey(atran.getExternalKey())) {
					taxlotStatus.remove( atran.getExternalKey() );
					taxlotStatus.put( atran.getExternalKey(), Boolean.TRUE );
                    log.info("Currently used Transaction Ids = "+atran.getExternalKey());
                }
			 }

			 // loop through list of taxlots for this security/portfolio
			 int row=0;
			 log.info("# taxlots: "+taxlotMap.size());
			 for ( Iterator i = taxlotMap.keySet().iterator(); i.hasNext(); row++) {
				// log.info("Adding row "+row);
				 OpenPosition position = (OpenPosition) taxlotMap.get( i.next() );
				 colnum=0;
                 data[row][colnum++]=position.getOpenDate();
				 data[row][colnum++]=position.getOpenValue();   
				 data[row][colnum++]=taxlotStatus.get( position.getExternalOpenTransactionId() );
                 data[row][colnum]=position.getExternalOpenTransactionId();
				 log.info("Transaction Id for row "+row+" = "+position.getExternalOpenTransactionId());
			 }

			 log.info("FINISHED LOADING TABLE DATA");
             CheckBoxTable model = new CheckBoxTable(data);
             table = new JTable(model);
             table.setAutoCreateRowSorter(true);
             table.setRowSelectionAllowed(true);
             table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
             CheckBoxTableRenderer renderer = new CheckBoxTableRenderer();
             renderer.setBackground(Color.DARK_GRAY);
             table.getColumnModel().getColumn(2).setCellRenderer(renderer);


             table.getColumnModel().getColumn(3).setPreferredWidth(0);
             TableColumn column = table.getColumnModel().getColumn(3);
             table.getColumnModel().removeColumn(column);
              logToUI("Ready");
             _transactionContainer.setViewportView(table);
             _transactionContainer.updateUI();
		} catch(Exception e) {
			 log.error("exception caught: "+e);
		}
    }
    private void showTransactionsforId() {
        operationId = Long.parseLong(_operationId.getText().trim());

        try{
            chanderOperation chanderop= operationController.getOperationByExternalId(Long.parseLong(_operationId.getText().trim()));
            chanderProductOperation op = (chanderProductOperation) chanderop;
            operationName=op.getchanderProduct().getSecurityName();
            operationDate=op.getAsOfDate().toString();
            showallPositions(chanderop);
          }
        catch(Exception e){
          logToUI("Error while Retiving Transtions, Operation ID might be wrong");
          log.error("exception caught while retriving from operationId "+e);
        }
    }

    /**
	 * updateTaxLots
	 * @param table
	 */
	private void updateTaxLots(JTable table) {

        logToUI("Updating tax lots for "+operationName+" on "+operationDate);
        List<Long> _addlist = new ArrayList<Long>();
		TableModel tabmodel = table.getModel();

        for(int j=0;j<noOfRows;j++) {
            if (table.getValueAt(j,2) == null)
				break;
				

            if (table.getValueAt(j,2).toString().equals("true")) {
                 _addlist.add((Long) tabmodel.getValueAt(table.convertRowIndexToModel(j),3));
            }
        }

		Collection<Long> addlist = new ArrayList<Long>(_addlist.size());
		for (Long uid : _addlist)
			addlist.add(uid);

		for (Long tids : addlist)
            log.info("Checked transaction Ids for updation "+tids);

            log.info("Updation Tax Lots for operation "+operationId);
            taxlotController.updateOperationTaxLots(operationId,addlist);
            logToUI("Tax lots were updated for "+operationName+" on "+operationDate);
    }



    /**
     * TaxLotShutdownHook inner class
     */
    protected class TaxLotShutdownHook extends Thread {
        private final Logger log = LogManager.getLogger(TaxLotShutdownHook.class);

        public void run() {

            log.info("Logging out of benport");

            try {
                context = (Context) ApplicationBeanFactory.getInstance().getBean("context");
                context.logout();
            } catch (Exception e) {
                log.error("could not cleanly shut down the app.");
            }
        }
    }

    /**
     * authenticated
     * Helper method to determine if currently logged into WF
     * @return true if WF user session is active, false otherwise
     */
    protected boolean authenticated() {
        return null != context && null != context.getAppUser();
    }

    /**
     * logToUI
     * Logs messages to the _status text area
     * @param s
     */
    private void logToUI(String s) {
        log.debug("before: "+_status.getFont());
        _status.setText(s);
        log.debug("after: "+_status.getFont());
        _status.updateUI();
    }
      

    /**
      * main
      * @param args
      */
    public static void main(String[] args) {

         try {
             UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()  );
         } catch (Exception e) {
             e.printStackTrace();
         }

         final TaxLotToolUI gui = new TaxLotToolUI();
         final JFrame frame = new JFrame("Tax Lot Picker");



         frame.setContentPane( gui.mainPanel );
         frame.pack();
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.setVisible(true);
         gui._transactionContainer.setVisible(false);
         gui._updateButton.setVisible(false);
         gui._Operations_Title.setVisible(false);
         gui._Transaction_Title.setVisible(false);
         gui._portfolioPanel.setVisible(false);
     }

}
class CheckBoxTableRenderer extends JCheckBox implements TableCellRenderer {



    protected CheckBoxTableRenderer()
	{
		setHorizontalAlignment(JCheckBox.CENTER);
		setVerticalAlignment(JCheckBox.CENTER);

    }


	public Component getTableCellRendererComponent(JTable table, Object value,
	        boolean isSelected, boolean hasFocus, int row, int col)
	{
	    setForeground(table.getForeground());
		setBackground(table.getBackground());

        setFont(table.getFont());
		setSelected((value != null && ((Boolean) value).booleanValue()));

      
        return this;
	}

}

error
Code:
Exception in thread "main" java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-16 18:23:46,285 INFO [com.chanderasset.ui.taxlot.forms.TaxLotToolUI$TaxLo tShutdownHook] Logging out of benport 2009-06-16 18:23:47,036 DEBUG [com.chanderasset.integration.utils.PropertyReader] properties.getString(context.login.username) = idris 2009-06-16 18:23:47,036 DEBUG [com.chanderasset.integration.utils.PropertyReader] properties.getString(context.login.password) = idris 2009-06-16 18:23:47,240 DEBUG [com.chanderasset.integration.vendors.benport.benportContext] Logging out of benport


Thanks
Idris
Last edited by admin : 18-Jun-2009 at 08:16. Reason: Please insert your example Java codes between [JAVA] and [/JAVA] tags
  #8  
Old 17-Jun-2009, 12:44
idrismca idrismca is offline
New Member
 
Join Date: Jun 2009
Posts: 5
idrismca is on a distinguished road

Re: Exception in thread "main" java.lang.NullPointerException


after i changed my log4j level to debug i also get this error besides the above errors.....


************************

log4j:WARN No appenders could be found for logger (org.springframework.context.s
upport.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.


**********************************************8


the log4j.xml is below

Code:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="true"> <!-- ================================= --> <!-- Preserve messages in a local file --> <!-- ================================= --> <!-- A simple file appender --> <appender name="FILE" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="c://work//chander//logs//myapp.log"/> <param name="Append" value="true"/> <param name="MaxFileSize" value="50MB"/> <param name="MaxBackupIndex" value="5"/> <param name="Threshold" value="DEBUG"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <!-- ============================== --> <!-- Append messages to the console --> <!-- ============================== --> <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender"> <param name="Threshold" value="DEBUG"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/> </layout> </appender> <!-- =============== --> <!-- Throttle Output --> <!-- =============== --> <!-- Limit the org.apache category to INFO as its DEBUG is verbose --> <category name="org.springframework" additivity="false"> <priority value="DEBUG"/> </category> <!-- Limit the org.apache category to INFO as its DEBUG is verbose --> <category name="org.apache" additivity="false"> <priority value="DEBUG"/> </category> <!-- Limit JBoss categories to INFO --> <category name="org.jboss" additivity="false"> <priority value="DEBUG"/> </category> <category name="com.dst" additivity="false"> <priority value="DEBUG"/> </category> <!-- ======================= --> <!-- Setup the Root category --> <!-- ======================= --> <root> <appender-ref ref="CONSOLE"/> <appender-ref ref="FILE"/> </root> </log4j:configuration>
  #9  
Old 17-Jun-2009, 14:19
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,141
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Exception in thread "main" java.lang.NullPointerException


I've never used log4j, but if you can get the debug to also provide the file and line#, then that would be helpful.

Post #8, is a WARNing, it can't seem to locate an appender based on the message it gives. I don't know what to tell you for that one.

=============

Post #7. Although there appears to be no line#'s, (probably a log4j option that's needs to be applied, and I don't know what that needs to be), but following the dump that was given, it appears that the problem is AFTER this statement:
JAVA Code:
java.lang.Runtime.getRuntime().addShutdownHook(new TaxLotShutdownHook());
// (might be useful to have a try/catch around this, by the way, based on Java's API's info)
The next statement after that:
JAVA Code:
_password.addKeyListener( // Hint: how/where is '_password' initialized?
HTH.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #10  
Old 17-Jun-2009, 15:01
idrismca idrismca is offline
New Member
 
Join Date: Jun 2009
Posts: 5
idrismca is on a distinguished road

Re: Exception in thread "main" java.lang.NullPointerException


i put try catch on all the listeners in the constructor..
i am using IntelliJ and things r working fine when i run from it... but now i m trying to make an executable jar which cna be used to run from other computers... it compiles well thru ant but when i try to run thru the command "java -jar example.jar" it gives me all these errors...

JAVA Code:

package com.chanderasset.ui.taxlot.forms;

import com.chanderasset.business.Context;
import com.chanderasset.business.ApplicationBeanFactory;
import com.chanderasset.business.model.portfolio.controller.OperationController;
import com.chanderasset.business.model.portfolio.controller.PortfolioController;
import com.chanderasset.business.model.portfolio.controller.TaxLotController;
import com.chanderasset.business.model.portfolio.controller.OperationArgs;
import com.chanderasset.business.model.portfolio.beans.chanderPortfolio;
import com.chanderasset.business.model.portfolio.beans.chanderOperation;
import com.chanderasset.business.model.portfolio.beans.chanderTransaction;
import com.chanderasset.business.model.portfolio.beans.OpenPosition;
import com.chanderasset.ui.util.SwingWorker;
import com.chanderasset.ui.model.OperationTable;
import com.chanderasset.ui.model.CheckBoxTable;
import com.chanderasset.business.model.fund.beans.chanderProductRedemptionOperation;
import com.chanderasset.business.model.fund.beans.chanderProductOperation;
import com.chanderasset.business.model.fund.controller.SecurityController;


import javax.swing.*;
import javax.swing.table.TableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableCellRenderer;


import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;

import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.util.List;


/**
 * com.chanderasset.ui.taxlot.forms
 *
 * @author chander
 * @version $Id: TaxLotToolUI.java,v 1.9 2009/06/09 15:39:21 ibaxamusa Exp $
 */
public class TaxLotToolUI {
    // logging
    private static final Logger log = LogManager.getLogger(TaxLotToolUI.class);

    // gui globals
    private JPanel mainPanel;
    private JTextField _username;
    private JPasswordField _password;
    private JButton _loginButton;
    private JPanel _loginPanel;
    private JPanel _portfolioPanel;
    private JComboBox _portfolioList;
    private JButton _retrieveOperationsButton;
    private JPanel PortfolioContainer;
    private JSeparator _loginSeperator;
    private JPanel _operationPanel;
    private JTextArea _status;
    private JTable _operationTable;
    private JScrollPane _operationContainer;
    private JScrollPane _transactionContainer;
    private JButton _updateButton;
    private JLabel _Transaction_Title;
    private JLabel _Operations_Title;
    private JTextField _operationId;
    private JButton _retriveTransactionsButton;
    private JPanel popupPanel;
    private JTable table;

    protected int noOfRows;
    protected Object[][] data;
    protected long operationId;
    protected String operationDate;
    protected String operationName;


    // app globals
    protected Context context;
    protected TaxLotController taxlotController = null;
    protected PortfolioController portfolioController = null;
    protected OperationController operationController = null;
    protected chanderPortfolio _currentPortfolio = null;
    protected Collection<chanderOperation> _currentOperations = null;
    protected Map<String,chanderPortfolio> portfolioMap = null;
    protected chanderProductRedemptionOperation productRedemptionOperation = null;
    protected SecurityController securityController =null;
    protected Map<Long,chanderOperation> _operationMap = new HashMap<Long,chanderOperation>();
    protected Collection<OpenPosition> openpositions=null;
    protected Collection<chanderTransaction> chanderTransaction=null;



    // constants
    private static final String ACTION_LOGIN = "ACTION_LOGIN";
    private static final String ACTION_RETRIEVE_OPERATIONS = "ACTION_RETRIEVE_OPERATIONS";
    private static final String ACTION_UPDATE = "ACTION_UPDATE";
    private static final String ACTION_RETRIEVE_TRANSACTIONS = "ACTION_RETRIEVE_TRANSACTIONS";




    /**
     * constructor
     */
    public TaxLotToolUI() {
        // add shutdown hook
     try{
        java.lang.Runtime.getRuntime().addShutdownHook(new TaxLotShutdownHook());
    }
        catch(Exception e){e.printStackTrace(); log.debug("in shutdown hook error "+e);}
       //i logToUI("");


        // TODO: remove these defaults
       // _username.setText("");
      //  _password.setText("");
           try{
              _password.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        benportLogin(_username.getText(), new String(_password.getPassword()));
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );
           }
           catch(Exception e){
                log.debug("before STACK TRACE");
                e.printStackTrace();
               log.debug("passowrd error "+e);
           }
        try{
        _loginButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_LOGIN.equals(e.getActionCommand())) {

                                SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        benportLogin(_username.getText(), new String(_password.getPassword()));
                                        return null;
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );
         }
           catch(Exception e){
                log.debug("before STACK TRACE 1");
                e.printStackTrace();
               log.debug("login button sction listener error "+e);
           }

         try{
        _loginButton.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        benportLogin(_username.getText(), new String(_password.getPassword()));
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );
    }catch(Exception e){
                log.debug("before STACK TRACE 2");
                e.printStackTrace();
               log.debug("\n login button keylisten  "+e);
           }



        try {
        _retrieveOperationsButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_RETRIEVE_OPERATIONS.equals(e.getActionCommand()) && _portfolioList.getSelectedIndex()>0) {

                                _currentPortfolio =  portfolioMap.get( _portfolioList.getSelectedItem() );
                                _operationContainer.setVisible(false);
                                _Operations_Title.setVisible(false);
                                _transactionContainer.setVisible(false);
                                _Transaction_Title.setVisible(false);
                                _updateButton.setVisible(false);
                                SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        return (Object) loadPortfolioOperations( _currentPortfolio );
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );
        }catch(Exception e){
                       log.debug("before STACK TRACE 3");
                       e.printStackTrace();
                      log.debug("\n retrive button actionlisten  "+e);
                  }



               try {


         _retriveTransactionsButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_RETRIEVE_TRANSACTIONS.equals(e.getActionCommand())) {
                                  _operationContainer.setVisible(false);
                                  _Operations_Title.setVisible(false);
                                  _transactionContainer.setVisible(true);
                                  _updateButton.setVisible(true);
                                 SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                       showTransactionsforId();
                                       return null;
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );

               }catch(Exception e){
                              log.debug("before STACK TRACE 4");
                              e.printStackTrace();
                             log.debug("\n retriveTRANS button action listen  "+e);
                         }



                      try {

         _retriveTransactionsButton.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                            _operationContainer.setVisible(false);
                            _Operations_Title.setVisible(false);
                            _transactionContainer.setVisible(true);
                            _updateButton.setVisible(true);
                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                        showTransactionsforId();
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );

                      }catch(Exception e){
                                     log.debug("before STACK TRACE 5");
                                     e.printStackTrace();
                                    log.debug("\n retrive trans button keylisten  "+e);
                                }



                             try {

        _operationId.addKeyListener(
                new KeyListener(){
                    public void keyTyped(KeyEvent e) {
                       if( e.getKeyCode() == KeyEvent.VK_ENTER ){

                        }
                    }

                    public void keyPressed(KeyEvent e) {
                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                        }
                    }

                    public void keyReleased(KeyEvent e) {

                        if( e.getKeyCode() == KeyEvent.VK_ENTER ){
                            _operationContainer.setVisible(false);
                            _Operations_Title.setVisible(false);
                            _transactionContainer.setVisible(true);
                            _updateButton.setVisible(true);
                            SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {
                                    showTransactionsforId();
                                        return null;
                                    }
                                };

                                workerThread.start();
                        }
                    }

                }
        );

                             }catch(Exception e){
                                            log.debug("before STACK TRACE 6");
                                            e.printStackTrace();
                                           log.debug("\n opid button keylisten  "+e);
                                       }



                                    try {

          _updateButton.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        if (null != e.getActionCommand())
                            if (ACTION_UPDATE.equals(e.getActionCommand()) ) {

                               _transactionContainer.setVisible(false);
                               _Transaction_Title.setVisible(false);
                               _updateButton.setVisible(false);
                                
                                SwingWorker workerThread = new SwingWorker() {
                                    public Object construct() {

                                        updateTaxLots(table);
                                        return null;
                                    }
                                };

                                workerThread.start();
                            }
                    }
                }
        );

                                    }catch(Exception e){
                                                   log.debug("before STACK TRACE 7");
                                                   e.printStackTrace();
                                                  log.debug("\n update button Actionlisten  "+e);
                                              }



   try {

        _operationContainer.addMouseListener(new MouseAdapter() {
               });

       }catch(Exception e){
        log.debug("before STACK TRACE 8");
        e.printStackTrace();
        log.debug("\n op contaier mouselisten  "+e);
        }







    }

    /**
     * benportLogin
     */
    protected void benportLogin(String username, String password) {
        // log in to benport
        logToUI("Logging in to benport...");
        try {
            context = (Context) ApplicationBeanFactory.getInstance().getBean("context");
        } catch (Exception e) {
            log.debug("context error"+e);
        }

        try {
            context.setUserName(_username.getText());
            context.setPassWord(new String(_password.getPassword()) );
            context.login();


            // get controllers
            portfolioController = (PortfolioController) ApplicationBeanFactory.getInstance().getBean("portfolioController");
            taxlotController = (TaxLotController) ApplicationBeanFactory.getInstance().getBean("taxlotController");
            operationController = (OperationController) ApplicationBeanFactory.getInstance().getBean("operationController");
            securityController=(SecurityController) ApplicationBeanFactory.getInstance().getBean("securityController");




        } catch (Exception e) {
            log.debug("Could not log in! "+e);
            logToUI("ERROR: Could not log in to benport!");
        }

        // post login
        if (authenticated()) {
            _loginPanel.setVisible(false);
            _portfolioPanel.setVisible(true);
            loadPortfolios();
        }


       logToUI("Ready.");
    }


    /**
     * loadPortfolios
     */
    private void loadPortfolios() {

        logToUI("Loading portfolio list...");

        try {
            Collection<chanderPortfolio> portfolios = portfolioController.getPortfolios("Real Time");
            portfolioMap = new HashMap<String,chanderPortfolio>();
            for (chanderPortfolio portfolio : portfolios) {
                _portfolioList.addItem( portfolio.getShortName() );
                portfolioMap.put( portfolio.getShortName(), portfolio );



            }
        } catch (Exception e) {
            log.debug("load portfolio error "+e);
            //
        }

        if (null != portfolioMap && !portfolioMap.isEmpty()) {
            _portfolioList.setEnabled(true);
            _retrieveOperationsButton.setEnabled(true);
            if(_portfolioList.getItemAt(0).equals("Please choose a Portfolio")){}else{
            _portfolioList.insertItemAt("Please choose a Portfolio",0);// blank
            log.info("porTTFOLIO");                                                   }
            _portfolioList.setSelectedIndex(0);
           _operationId.setEnabled(true);
            _operationId.setEditable(true);
            _retriveTransactionsButton.setEnabled(true);
            logToUI("Portfolio list retrieved.");
        }
    }

    /**
     * loadOperations
     * @param portfolio The portfolio object
     * @return list of operations
     */
    private Collection<chanderOperation> loadPortfolioOperations(chanderPortfolio portfolio) {
        log.info("Loading portfolio operations for "+portfolio.getShortName());
        Collection<chanderOperation>  operations = null;

        OperationArgs opQuery = new OperationArgs();
        opQuery.setPortfolioId( portfolio.getExternalPortfolioId() );
        opQuery.justEstimated();
        opQuery.justRedemption();

        logToUI("Loading operations for "+portfolio.getShortName()+"...");
        try {
            operations = operationController.getOperations(opQuery);
        } catch (Exception e) {
            log.debug("Could not load operations: "+e,e);
        }


        if (null != operations) {

            for (chanderOperation operation : operations) {
                _operationMap.put( operation.getExternalOperationId(), operation);
            }

            logToUI("Found "+operations.size()+" operations in "+portfolio.getShortName()+".");

            _operationContainer.setEnabled(true);
            JTable _operationList = new JTable(new OperationTable(operations));

            setupTable(_operationList);

            _operationContainer.setViewportView(_operationList);
            _operationContainer.updateUI();
        }

            _operationContainer.setVisible(true);
            _Operations_Title.setVisible(true);
            _Operations_Title.setText("Operations for "+portfolio.getShortName());
            _Operations_Title.updateUI();

        return operations;
    }


    /**
     * setupColumnWidths
     * this is ugly but a WIP.
     */
    private void setupTable(final JTable table) {
        table.getColumnModel().getColumn(0).setPreferredWidth(100);
        table.getColumnModel().getColumn(1).setPreferredWidth(350);
        table.getColumnModel().getColumn(2).setPreferredWidth(100);
        table.getColumnModel().getColumn(3).setPreferredWidth(250);
        table.getColumnModel().getColumn(4).setPreferredWidth(100);
       
        TableColumn column = table.getColumnModel().getColumn(4);
        table.getColumnModel().removeColumn(column);
        //CheckBoxTableRenderer renderer = new CheckBoxTableRenderer();
		//renderer.setHorizontalAlignment(SwingConstants.RIGHT);
		//table.getColumnModel().getColumn(1).setCellRenderer(renderer);
        table.setAutoCreateRowSorter(true);
        
        table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {

					int maxRows;
					int[] selRows;
					Object value;

					_transactionContainer.setVisible(true);
                    _updateButton.setVisible(true);
                    selRows = table.getSelectedRows();
					TableModel tm;
					tm = table.getModel();
					if (selRows.length > 0) {
						for (int i= 0; i < 4 ; i++) {
						  // get Table data
                            value=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),i);
                        }
					}

					value=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),4);
                    String s=value.toString();
					operationId = Long.parseLong(s.trim());
                    operationName=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),1).toString();
                    operationDate=tm.getValueAt(table.convertRowIndexToModel(selRows[0]),2).toString();
                    log.info("Loading positions for operation"+operationId);
					showallPositions(_operationMap.get(operationId));
				}
			}
     	});
    }

    private void createUIComponents() {
        // TODO: place custom component creation code here
    }


    private void showallPositions(chanderOperation chanderOperation) {

		log.info("Showing all positions for operation "+chanderOperation.getExternalOperationId());
        chanderProductRedemptionOperation chanderproductRedemptionOperation=(chanderProductRedemptionOperation) chanderOperation;
        chanderTransaction=chanderproductRedemptionOperation.getOpenTransactions();
        log.info("DATEI "+chanderOperation.getAsOfDate());
        Date _asOfDate, _daybefore;
        Calendar calendar;

            _asOfDate = chanderOperation.getAsOfDate();
            calendar = Calendar.getInstance();
            calendar.setTime(_asOfDate);
            calendar.add(Calendar.DATE, -1);
            _daybefore = calendar.getTime();

        openpositions = taxlotController.getAvailableTaxLots(chanderproductRedemptionOperation.getExternalProductId(),chanderOperation.getExternalPortfolioId(),_daybefore) ;
		log.info("FOUND "+(null != openpositions ? openpositions.size() : 0) + " OPEN POSITIONS");

         try {
             _transactionContainer.setVisible(true);
             _Transaction_Title.setVisible(true);
             _Transaction_Title.setText("Tax Lots for "+operationName +" as of "+operationDate);
             _Transaction_Title.updateUI();

             int rownum=0;
             int colnum=0;
             noOfRows=openpositions.size();
			 log.info("openpositions.size() ="+noOfRows);


             data = new Object[noOfRows][4];

			 // loop through all available transactions
			 Map taxlotMap = new HashMap();
			 Map taxlotStatus = new HashMap();
			 for (OpenPosition openposition : openpositions) {
				taxlotStatus.put( openposition.getExternalOpenTransactionId(), Boolean.FALSE );
				taxlotMap.put( openposition.getExternalOpenTransactionId(), openposition );
			 }
			 log.info("taxlotStatus.size="+taxlotStatus.size());

			 // toggle flag on transactions currently linked to the operation
			 for (chanderTransaction atran : chanderTransaction) {
				if (taxlotStatus.containsKey(atran.getExternalKey())) {
					taxlotStatus.remove( atran.getExternalKey() );
					taxlotStatus.put( atran.getExternalKey(), Boolean.TRUE );
                    log.info("Currently used Transaction Ids = "+atran.getExternalKey());
                }
			 }

			 // loop through list of taxlots for this security/portfolio
			 int row=0;
			 log.info("# taxlots: "+taxlotMap.size());
			 for ( Iterator i = taxlotMap.keySet().iterator(); i.hasNext(); row++) {
				// log.info("Adding row "+row);
				 OpenPosition position = (OpenPosition) taxlotMap.get( i.next() );
				 colnum=0;
                 data[row][colnum++]=position.getOpenDate();
				 data[row][colnum++]=position.getOpenValue();   
				 data[row][colnum++]=taxlotStatus.get( position.getExternalOpenTransactionId() );
                 data[row][colnum]=position.getExternalOpenTransactionId();
				 log.info("Transaction Id for row "+row+" = "+position.getExternalOpenTransactionId());
			 }

			 log.info("FINISHED LOADING TABLE DATA");
             CheckBoxTable model = new CheckBoxTable(data);
             table = new JTable(model);
             table.setAutoCreateRowSorter(true);
             table.setRowSelectionAllowed(true);
             table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
             CheckBoxTableRenderer renderer = new CheckBoxTableRenderer();
             renderer.setBackground(Color.DARK_GRAY);
             table.getColumnModel().getColumn(2).setCellRenderer(renderer);


             table.getColumnModel().getColumn(3).setPreferredWidth(0);
             TableColumn column = table.getColumnModel().getColumn(3);
             table.getColumnModel().removeColumn(column);
              logToUI("Ready");
             _transactionContainer.setViewportView(table);
             _transactionContainer.updateUI();
		} catch(Exception e) {
			 log.debug("exception caught: "+e);
		}
    }
    private void showTransactionsforId() {
        operationId = Long.parseLong(_operationId.getText().trim());

        try{
            chanderOperation chanderop= operationController.getOperationByExternalId(Long.parseLong(_operationId.getText().trim()));
            chanderProductOperation op = (chanderProductOperation) chanderop;
            operationName=op.getchanderProduct().getSecurityName();
            operationDate=op.getAsOfDate().toString();
            showallPositions(chanderop);
          }
        catch(Exception e){
          logToUI("Error while Retiving Transtions, Operation ID might be wrong");
          log.debug("exception caught while retriving from operationId "+e);
        }
    }

    /**
	 * updateTaxLots
	 * @param table
	 */
	private void updateTaxLots(JTable table) {

        logToUI("Updating tax lots for "+operationName+" on "+operationDate);
        List<Long> _addlist = new ArrayList<Long>();
		TableModel tabmodel = table.getModel();

        for(int j=0;j<noOfRows;j++) {
            if (table.getValueAt(j,2) == null)
				break;
				

            if (table.getValueAt(j,2).toString().equals("true")) {
                 _addlist.add((Long) tabmodel.getValueAt(table.convertRowIndexToModel(j),3));
            }
        }

		Collection<Long> addlist = new ArrayList<Long>(_addlist.size());
		for (Long uid : _addlist)
			addlist.add(uid);

		for (Long tids : addlist)
            log.info("Checked transaction Ids for updation "+tids);

            log.info("Updation Tax Lots for operation "+operationId);
            taxlotController.updateOperationTaxLots(operationId,addlist);
            logToUI("Tax lots were updated for "+operationName+" on "+operationDate);
    }



    /**
     * TaxLotShutdownHook inner class
     */
    protected class TaxLotShutdownHook extends Thread {
        private final Logger log = LogManager.getLogger(TaxLotShutdownHook.class);

        public void run() {

            log.info("Logging out of benport");

            try {
                context = (Context) ApplicationBeanFactory.getInstance().getBean("context");
                context.logout();
            } catch (Exception e) {
                log.debug("could not cleanly shut down the app. "+e);
            }
        }
    }

    /**
     * authenticated
     * Helper method to determine if currently logged into WF
     * @return true if WF user session is active, false otherwise
     */
    protected boolean authenticated() {
        return null != context && null != context.getAppUser();
    }

    /**
     * logToUI
     * Logs messages to the _status text area
     * @param s
     */
    private void logToUI(String s) {
        log.debug("before: "+_status.getFont());
        _status.setText(s);
        log.debug("after: "+_status.getFont());
        _status.updateUI();
    }
      

    /**
      * main
      * @param args
      */
    public static void main(String[] args) {

         try {
             UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()  );
         } catch (Exception e) {
             e.printStackTrace();
             log.debug("error in MAIN "+e);
         }

         final TaxLotToolUI gui = new TaxLotToolUI();
         final JFrame frame = new JFrame("Tax Lot Picker");



         frame.setContentPane( gui.mainPanel );
         frame.pack();
         frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         frame.setVisible(true);
         gui._transactionContainer.setVisible(false);
         gui._updateButton.setVisible(false);
         gui._Operations_Title.setVisible(false);
         gui._Transaction_Title.setVisible(false);
         gui._portfolioPanel.setVisible(false);
     }

}
class CheckBoxTableRenderer extends JCheckBox implements TableCellRenderer {



    protected CheckBoxTableRenderer()
	{
		setHorizontalAlignment(JCheckBox.CENTER);
		setVerticalAlignment(JCheckBox.CENTER);

    }


	public Component getTableCellRendererComponent(JTable table, Object value,
	        boolean isSelected, boolean hasFocus, int row, int col)
	{
	    setForeground(table.getForeground());
		setBackground(table.getBackground());

        setFont(table.getFont());
		setSelected((value != null && ((Boolean) value).booleanValue()));

      
        return this;
	}

}


dump is as


Code:
2009-06-17 15:43:14,925 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:14,941 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] pas owrd error java.lang.NullPointerException 2009-06-17 15:43:14,941 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 1 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:14,941 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] log n button sction listener error java.lang.NullPointerException 2009-06-17 15:43:14,941 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 2 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] login button keylisten java.lang.NullPointerException 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 3 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] retrive button actionlisten java.lang.NullPointerException 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 4 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] retriveTRANS button action listen java.lang.NullPointerException 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 5 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] retrive trans button keylisten java.lang.NullPointerException 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 6 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:14,956 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] opid button keylisten java.lang.NullPointerException 2009-06-17 15:43:15,035 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 7 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:15,035 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] update button Actionlisten java.lang.NullPointerException 2009-06-17 15:43:15,035 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] bef re STACK TRACE 8 java.lang.NullPointerException at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.<init>(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:15,035 DEBUG [com.chanderasset.ui.taxlot.forms.TaxLotToolUI] op contaier mouselisten java.lang.NullPointerException Exception in thread "main" java.awt.IllegalComponentStateException: contentPane cannot be set to null. at javax.swing.JRootPane.setContentPane(Unknown Source) at javax.swing.JFrame.setContentPane(Unknown Source) at com.chanderasset.ui.taxlot.forms.TaxLotToolUI.main(Unknown Source) 2009-06-17 15:43:16,037 INFO [com.chanderasset.ui.taxlot.forms.TaxLotToolUI$TaxL tShutdownHook] Logging out of benport log4j:WARN No appenders could be found for logger (org.springframework.context. upport.ClassPathXmlApplicationContext). log4j:WARN Please initialize the log4j system properly. 2009-06-17 15:43:16,836 DEBUG [com.chanderasset.integration.utils.PropertyReader] properties.getString(context.login.username) = chander 2009-06-17 15:43:16,836 DEBUG [com.chanderasset.integration.utils.PropertyReader] properties.getString(context.login.password) = yourmom 2009-06-17 15:43:17,071 DEBUG [com.chanderasset.integration.vendors.benport.Webf lioContext] Logging out of benport
 
 

Recent GIDBlogOnce again, no time for hobbies by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

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

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Thread Stopping Exception Gix .NET Forum 12 28-Nov-2006 05:30
Thread itch C++ Forum 7 10-May-2006 16:10
please help in solving: Exception in thread "main" java.lang.nullpointerexception vkiran_v Java Forum 8 09-May-2006 08:06
C++ Copy Constructor & Exception issues greymalkin C++ Forum 3 05-Oct-2005 22:36
Sending message to GUI thread that ISNT the main thread mpviii MS Visual C++ / MFC Forum 1 20-Apr-2005 13:49

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 01:59.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.