| Threads java.lang.NullPointerException |
|
 |
Index ‹ java-programmer
|
- Previous
- 2
- Thread garbage collectionWhat happens if a Thread is available for garbage collection yet still
running?
I guess the answer is obvious. The thread executes to completion or is
terminated with the garbage collection process at some later unguaranteed
time. Correct?
I'm asking because I'm reusing the same reference to a thread to create a
new one on an event. I just realized that I'm probably leaving a ton of
orphaned threads (which will soon be fixed).
Thanks!
- 2
- flicker when dragging over a jtree nodeWhen I drag onto a row (not neccessary over the node icon), the
tree node icon looked flicker. Is there any way to prevent this?
Is there anything to do with dragOver?
thanks
- 2
- 2
- I want to pre-compile ALL JSPs in my applicationHi
Is there any simple way to tell Tomcat to precompile _all_ JSPs in my
application? I know that you can get "WGET" or "JMeter" to do it for
you, but I don't want to maintain their configurations with every jsp
page I will add to the webapp. Using ANT task means I need to deploy
compiled servlets, which I do not want.
Thanks
- 3
- Beta Test AnnouncementI have spent many hours (years!) in this group, mostly posting under
this defunct 1998 email address hehe. Our current project is in a
'closed' beta test here:
www.starprog.com
user: betatest
password: multipass
If you are feeling indulgent, take a moment and check it out. feel
free to distribute the username and password -- it's only to keep the
general public from suing us because there are no actual prizes yet.
Thanx!
(there is a contact form on the site to comment directly without
giving your email)
clh
- 6
- SWT and public fieldsIf you browse through the JavaDoc documentation for the SWT graphical user
interface toolkit, it won't be long before you descover that public fields
are used in many places. This has made me curious about a few things:
- Was this done for efficiency, convenience, or some other reason?
- Does this represent a trend away from a style of strict encapsulation?
- Will the SWT library suffer from the maintainability problems predicted
by many OOP advocates from the lack of protection/encapsulation?
- Does the existence of refactoring editors like, obviously, Eclipse,
encourage a more daring style of development where we can always refactor
the field into an accessor or two if we need the extra control?
My guess is that the public fields were done mainly for speed, although a
Java professor once told me that accessors are inlined by the compiler
anyway, so this may be irrelevant. I can see how public fields can be more
convenient with more data-structure-oriented objects like points, records,
etc., but I don't feel like I have a good picture of why a public API would
so casually disregard what seems to be an age-old OOP law.
Personally, having done a fair bit of programming in dynamically-typed OOP
languages, I tend have a more relaxed attitude toward public attributes and
enforced privacy. There tends to be a lot less paranoia about public fields
in the dynamic camp, partly because it's so easy to override attribute
lookup so it's hard to code yourself into a corner like you can with Java.
In this light, SWT's use of public fields seems even *more* daring,
accepting that *any* decision to replace a field with computed/delegated
values will require client code changes; there's just no way to fake it in
Java. For a library as big as the SWT, this surprises me.
What do you think about this? Do you think this will cause maintenance
problems for SWT? Is there any evidence that this has caused problems
already? Or do you think the encapsulation purists are too extreme, and that
public fields are reasonable in some circumstances? If so, what circumstances?
Thanks for your input,
Dave
--
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
- 7
- Need Abinito and Tibco (5) - Req.Hi,
These are the requirements currently open.
Req. ID: Req-030520081038 - Ab initio Developer
Primary Skills: Abinitio, ETL, ORACLE,GDE (Ab-initio), SQL * Net, Net
8, SQL * Loader, SQL * Plus, Oracle DBA Studio, ODBC
Secondary Skills: Unix & Windows NT
Description: Must have strong ETL development background and object
oriented analysis and design experience. Atleast 1 to 2 years of
Abinitio experience is required. Strong experience in Perl, Shell
scripting, SQL, PL/SQL and other programming languages and be able to
optimize and tune complex queries. Oracle 9i design, data model
maintenance and data loading experience is required. Strong
interpersonal and communication skills (both written and verbal) are
required. Ability to work nights and weekends when necessary due to
project deadlines and support issues is required.
Knowledge of AS400, Web Methods, BI tools like Business Objects and
Project
Rate: Open, Job Type: Contract, Total Exp: 6 Years, Duration: 1
Year, Number Of Openings: 1, Location: Chicago-IL
Req. ID: Req-030520081040 - Tibco Developers (5)
Description:
3 years experience in a complex business and information systems
environment
2+ years Tibco BusinessWorks Experience
2+ years of Web Services experience (XML/SOAP/WSDL)
Eclipse-based IDE experience for coding, testing, debugging of Java
applications.
1+ years of JDBC programming experience with oracle preferred
Experience developing technical design specifications in a structure
development methodology
Outstanding oral, written, and presentation skills
Ability to work collaboratively with diverse groups
Ability to travel up to 10% of the time
Comfortable in both a UNIX and windows based environment
Rate: Open, Job Type: Contract, Duration: 6 Months, Number Of
Openings: 5, Location: St. Louis, MO
I will contact you, if I need more information.
Regards
Craig
- 9
- 11
- Java to XMLIs there a parser which converts Java Source Code to XML?
--
Sebastian Danicic web: http://www.doc.gold.ac.uk/~mas01sd
Department of Computing, e-mail: email***@***.com
Goldsmiths College, Dept web: http://www.doc.gold.ac.uk
University of London, tel +44(0)207 9197868
London SE14 6NW. fax +44(0)870 0514569
- 13
- Problem with Struts' SwitchActionHi all!
I have problem with SwitchAction. Simplified workflow is following:
- main module (struts-config.xml):
/start.do (SwitchAction, passed params: prefix=/module1; page=/search.jsp)
This action is used to properly enter Struts framework.
- /module1 module (struts-config-module1.xml):
Form in search.jsp submits to the following action:
/module1/search.do (SwitchAction, passed params: prefix=/search;
page=/search.do)
This action switches to the search module.
- /search module (struts-config-search.xml):
/search/search.do (SearchAction)
SearchAction is custom action and it forwards to the another SwitchAction in
the /search module (/search/performSearch.do). SwitchAction params are added
within SearchAction to the path.
/search/performSearch.do (SwitchAction passed params: prefix=/module1;
page=/performSearch.do)
Now here occurs the problem. When SwitchAction of the
/search/performSearch.do action seeks for prefix param from the request
object, it gets old value "/search". Somehow value "/module1" is lost,
although I have set it in the SearchAction. This results with infinite loop,
because Struts does not switch from /search module to /module1 module and
/performSearch exists in both modules.
So, somehow when I chain my SearchAction and SwitchAction, new value of the
prefix param which is passed to the SwitchAction is lost.
Platform is WSAD 5.1.
Thanks,
BB
- 13
- Looking for HTML Rendererhi,
i'm looking for a HTML rendered for java. some functionalities i want
are (1) be able to access the DOM tree for the HTML file and (2) given
some DOM object, find out its physical location (and maybe other
properties like color, size, etc) on the rendered page.
i know this is possible through IE but unfortunately, i can't use IE.
JRex (http://jrex.mozdev.org/) *seems* like it has what i want but i've
read that it doesn't satisfy (2). does anyone know how to achieve this?
thank you.
--
Xiaolei Li | email***@***.com | www.xiaolei.org
- 13
- Accessing initParam variables from a classMy apologies if this is not the correct forum for this question:
I have a Tomcat server and I'm trying to develop an application that
accesses a SQL server from a java class.
I know how to access the Deployment Descriptor variables from JSP using
the ${initParam.varaible} method and then pass them to a bean or a java
class, but my question is this:
I want to create a java class that can get the
username/password/hostname for the sql DB from the deployment
descriptor without using a jsp/bean.
Is there a method that will allow me access the Deployment Descriptor
variables directly from a java class in my project?
Thanks much
-Aaron
- 16
- java applet html editorMicrosoft has provided lots of tools to develop web base html editors
for their developers... it's called MSHTML.
this language, has text selection, replace, hyperlinks, etc...
the problem with it, it's it does not work on any other platform. Just
windows with ie. That is ok, because in that case you cover at least
85% of the market. But still, it's not good enough...
is there anywhere i can find code example on developping a java applet
that edits HTML online? feed it with html content, modify the content
with BOLD, ITALIC etc... buttons, and get resultig html.
I've looked around, i've found some examples:
http://www.hotscripts.com/Java/Applets/Content_Management/
but all these examples cost a lot of $$$. it's bizarre...
I wonder if there any software i can use to decompile these examples
above and look at the code??? somebody, somewhere either has the code,
or is willing to sell an applet at a reasonable price...
Please let me know.
Tascien
- 16
- thread errori face the following error..
i have a JTextPanel and a thread that checks every 1sec if there is data
in an imputstream and write them to the text panel.. i have also a
button with which i want to "pause" the thread...
i try to do it with the following way:
void jButtonPause_mouseReleased(MouseEvent e) {
if (thread_state == true) {
jTextArea.append("\n try to stop thread \n");
try {
synchronized (this) {
t.notify();
t.wait();
}
thread_state = false;
jButtonPause.setText("Resume");
}
catch (InterruptedException ex) {
jTextArea.append(ex.getMessage());
}
}
else {
synchronized (this) {
t.notify();
}
thread_state = true;
jButtonPause.setText("Pause");
}
}
the above is the code for the button. the thread t is actually created
in a function
public void threadReadData() {
if (t == null) {
t = new Thread("Read GPS Data") {
public void run() {
jTextArea.setText("");
.
.
.
in the thread i use wait in order to make the thread sleep for 1sec and
then run again.
And now the problem.. when i press the button i get a
java.lang.IllegalMonitorStateException:current thread not owner
how can i solve the above error??
Best regards
Mandilas Antonis
- 16
- Ant Exec task- getting back execution value into resultpropertyHi,
I am using CruiseControl over Ant and I am running an Exec task that
runs a perl script that returns at exit "0" or "1" to determine
execution status.
My problem is that the resultproperty that suppose to get the returned
code does not change after execution.
The Exec task looks like that:
<property name="BuildStatus" value="123"/>
<echo message="Build status before=${BuildStatus}" />
<exec executable="perl"
failonerror="false"
failifexecutionfails="false"
resultproperty="${BuildStatus}"
output="output.txt"
dir="/scripts/">
<arg line="BuildAll.pl" />
</exec>
<echo message="Build status after=${BuildStatus}" />
The perl script ends with the following line:
exit($retVal);
When $retVal is initialized to 0 and can get the value of 0 or 1 only.
On the 2 prints surrounding the exec task I get the same value of
${BuildStatus} which is the one it was initialized with (123).
I tried initializing the property in the start of the Ant build file.
same results.
I tried using the attributes: outputproperty and errorproperty in order
to catch the return code. It didn't helped.
my purpose with this, is to fail the build at the end of it based on
the value returned from the perl script.
Ant-1.6.5
CruiseControl- 2.5.0
Java-1.5.0_06
Platform- MacBook, 1.83 Duo, 1GB Ram
Thanks,
Itai Barami.
|
| Author |
Message |
Max010

|
Posted: 2005-8-22 16:40:00 |
Top |
java-programmer, Threads java.lang.NullPointerException
Hi there I was wondering if anyone can help me please.
I ve been working on a simple chat server program and it works when the
server handles one client at the time. I ve been trying to make the
server able to answer clients requests at the same time with threads.
I always get the same error message when I run the server:
java.lang.NullPointerException
at chatserverq3.ServerGUI.processClientRequests(ServerGUI.java:113)
at chatserverq3.ServerGUI.run(ServerGUI.java:73)
at java.lang.Thread.run(Thread.java:484)
This is the client code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ClientGUI extends JFrame implements ActionListener
{
private JTextField nameField;
private JLabel nameLabel;
private JLabel areaLabel;
private JPanel topPanel, botPanel;
private JButton connectButton;
private JTextArea listArea;
private InputStream is;
private OutputStream os;
private BufferedReader fromServer;
private Socket socket;
private PrintWriter toServer;
static final String SERVER_ADDRESS = "127.0.0.1";
static final int SERVER_PORT_NUMBER = 4000;
static final String CLIENT_LOGGINGOFF = "Exit";
//constructor for the client GUI
public ClientGUI(String title)
{
setSize(400, 400);
setTitle(title);
setLocation(100, 100);
nameLabel = new JLabel("Name");
nameField = new JTextField(10);
areaLabel = new JLabel("Connected Users");
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
botPanel = new JPanel();
connectButton = new JButton("Connect");
connectButton.addActionListener(this);
listArea = new JTextArea(10, 30);
JScrollPane scr = new JScrollPane(listArea);
topPanel.add(nameField, "West");
topPanel.add(nameLabel, "Center");
topPanel.add(connectButton, "East");
botPanel.add(areaLabel);
botPanel.add(listArea);
getContentPane().add(topPanel, "North");
getContentPane().add(botPanel, "Center");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//attempts to connect the client to the server
private void connectServer()
{
try
{
socket = new Socket(SERVER_ADDRESS, SERVER_PORT_NUMBER);
openStreams();
}
catch(IOException e)
{
System.out.println("Trouble contacting the server " + e);
}
}
private void open()throws IOException
{
final boolean AUTO_FLUSH = true;
is = socket.getInputStream();
fromServer = new BufferedReader(new InputStreamReader(is));
os = socket.getOutputStream();
toServer = new PrintWriter(os, AUTO_FLUSH);
}
//action performed when the client GUI button is pressed
public void actionPerformed(ActionEvent a)
{
String buttonLabel = connectButton.getText();
String userName = nameField.getText();
try
{
if((buttonLabel == "Connect")&&(userName.length()> 0))
{
connectToServer();
sendUserName(userName);
connectButton.setText("Disconnect");
}
else
{
logOff(userName);
connectButton.setText("Connect");
}
}
catch(IOException e)
{
System.out.println("Problem with the server " + e);
}
}
private void close()throws IOException
{
toServer.close();
os.close();
fromServer.close();
is.close();
}
//sends the user name to the server
private void sendUserName(String aName)throws IOException
{
String reply;
String uName = aName;
toServer.println(uName + " logged on");
reply = fromServer.readLine();
listArea.setText(reply);
}
//notifies the server a client has logged off
private void logOff(String aName)throws IOException
{
String uName = aName;
toServer.println(uName + " logged off");
listArea.setText("");
toServer.println(CLIENT_LOGGINGOFF);
closeStreams();
socket.close();
}
}
public class Main {
public static void main(String[] args)
{
ClientGUI cg = new ClientGUI("ChatClient");
cg.setVisible(true);
}
}
The server code is:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ServerGUI extends JFrame implements Runnable
{
private JTextArea logArea;
private JLabel logLabel;
private JPanel logPanel;
private ServerSocket ss;
private Socket socket;
private InputStream is;
private OutputStream os;
private PrintWriter toClient;
private BufferedReader fromClient;
static final int PORT_NUMBER = 4000;
static final String CLIENT_LOGGINGOFF = "Exit";
//constructor for the Server GUI
public ServerGUI(String title)
{
setSize(400, 400);
setTitle(title);
setLocation(100, 100);
logArea = new JTextArea(15, 30);
JScrollPane scr = new JScrollPane(logArea);
logLabel = new JLabel("Logging history");
logPanel = new JPanel();
logPanel.add(logLabel);
logPanel.add(logArea);
getContentPane().add(logPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//constructor for the server to set the socket to handle a new thread
public ServerGUI(Socket s)
{
socket = s;
}
public void run()
{
try
{
while(true)
{
openStreams();
processClientRequests();
closeStreams();
socket.close();
}
}
catch(IOException e)
{
System.out.println("Trouble with a connection " + e);
}
}
//helper method for the class to set up the streams
private void open() throws IOException
{
final boolean AUTO_FLUSH = true;
is = socket.getInputStream();
fromClient = new BufferedReader(new InputStreamReader(is));
os = socket.getOutputStream();
toClient = new PrintWriter(os, AUTO_FLUSH);
}
//process the string from received from each client
private void processRequests() throws IOException
{
String userName;
String reply;
int numberOfFields = 3;
String [] fieldContents = new String[numberOfFields];
userName = fromClient.readLine();
while(!(userName.equals(CLIENT_LOGGINGOFF)))
{
StringTokenizer tokensIn = new StringTokenizer(userName, " ");
int i = 0;
while(tokensIn.hasMoreTokens())
{
fieldContents[i] = tokensIn.nextToken();
i++;
}
reply = fieldContents[0];
toClient.println(reply);
logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
"+fieldContents[2]+"\n");
userName = fromClient.readLine();
}
}
//helper method to close the streams with each client
private void close() throws IOException
{
toClient.close();
os.close();
fromClient.close();
is.close();
}
}
import java.net.*;
import java.io.*;
public class ChatHandler
{
static final int PORT_NUMBER = 4000;
public ChatHandler()
{
}
public void run()
{
try
{
ServerSocket server = new ServerSocket(PORT_NUMBER);
while(true)
{
Socket client = server.accept ();
System.out.println ("Accepted from " + client.getInetAddress ());
Thread aThread = new Thread(new ServerGUI(client));
aThread.start ();
}
}
catch(IOException e)
{
System.out.println("Trouble with ServerSocket, port
"+PORT_NUMBER +": " + e);
}
}
}
public class Main {
public static void main(String[] args)
{
ServerGUI sg = new ServerGUI("ChatServer");
sg.setVisible(true);
ChatHandler cH = new ChatHandler();
cH.run();
}
}
It is the first time I use threads and maybe there is something I dont
understand. Can anyone point me to the right direction please? I think
the problem may be with the 2 server constructor but I am not sure how
to solve it.
Cheers Pat
|
| |
|
| |
 |
Sean

|
Posted: 2005-8-22 18:25:00 |
Top |
java-programmer >> Threads java.lang.NullPointerException
On
>Hi there I was wondering if anyone can help me please.
>
>I ve been working on a simple chat server program and it works when the
>server handles one client at the time. I ve been trying to make the
>server able to answer clients requests at the same time with threads.
>
>I always get the same error message when I run the server:
>
>java.lang.NullPointerException
>
>at chatserverq3.ServerGUI.processClientRequests(ServerGUI.java:113)
>
> at chatserverq3.ServerGUI.run(ServerGUI.java:73)
>
> at java.lang.Thread.run(Thread.java:484)
>
>This is the client code:
>
>import java.awt.*;
>import javax.swing.*;
>import java.awt.event.*;
>import java.io.*;
>import java.net.*;
>
>
>public class ClientGUI extends JFrame implements ActionListener
>{
> private JTextField nameField;
> private JLabel nameLabel;
> private JLabel areaLabel;
> private JPanel topPanel, botPanel;
> private JButton connectButton;
> private JTextArea listArea;
>
> private InputStream is;
> private OutputStream os;
> private BufferedReader fromServer;
> private Socket socket;
> private PrintWriter toServer;
>
>
> static final String SERVER_ADDRESS "127.0.0.1";
> static final int SERVER_PORT_NUMBER 4000;
> static final String CLIENT_LOGGINGOFF "Exit";
>
>//constructor for the client GUI
> public ClientGUI(String title)
> {
> setSize(400, 400);
> setTitle(title);
> setLocation(100, 100);
> nameLabel new JLabel("Name");
> nameField new JTextField(10);
> areaLabel new JLabel("Connected Users");
> topPanel new JPanel();
> topPanel.setLayout(new BorderLayout());
> botPanel new JPanel();
> connectButton new JButton("Connect");
> connectButton.addActionListener(this);
> listArea new JTextArea(10, 30);
> JScrollPane scr new JScrollPane(listArea);
>
> topPanel.add(nameField, "West");
> topPanel.add(nameLabel, "Center");
> topPanel.add(connectButton, "East");
>
> botPanel.add(areaLabel);
> botPanel.add(listArea);
>
> getContentPane().add(topPanel, "North");
> getContentPane().add(botPanel, "Center");
>
> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
>
> }
>
> //attempts to connect the client to the server
> private void connectServer()
Change to connectToServer?
> {
> try
> {
> socket new Socket(SERVER_ADDRESS, SERVER_PORT_NUMBER);
> openStreams();
I can't find this method. Do you mean to call open()?
> }
> catch(IOException e)
> {
> System.out.println("Trouble contacting the server " + e);
> }
> }
>
> private void open()throws IOException
> {
> final boolean AUTO_FLUSH true;
> is socket.getInputStream();
> fromServer new BufferedReader(new InputStreamReader(is));
> os socket.getOutputStream();
> toServer new PrintWriter(os, AUTO_FLUSH);
> }
>
>//action performed when the client GUI button is pressed
> public void actionPerformed(ActionEvent a)
> {
> String buttonLabel connectButton.getText();
> String userName nameField.getText();
> try
> {
> if((buttonLabel "Connect")&&(userName.length()> 0))
> {
> connectToServer();
> sendUserName(userName);
> connectButton.setText("Disconnect");
> }
> else
> {
> logOff(userName);
> connectButton.setText("Connect");
> }
>
> }
> catch(IOException e)
> {
> System.out.println("Problem with the server " + e);
> }
> }
>
> private void close()throws IOException
> {
> toServer.close();
> os.close();
> fromServer.close();
> is.close();
> }
>
> //sends the user name to the server
> private void sendUserName(String aName)throws IOException
> {
> String reply;
> String uName aName;
> toServer.println(uName + " logged on");
>
> reply fromServer.readLine();
> listArea.setText(reply);
> }
>
>//notifies the server a client has logged off
> private void logOff(String aName)throws IOException
> {
> String uName aName;
> toServer.println(uName + " logged off");
> listArea.setText("");
> toServer.println(CLIENT_LOGGINGOFF);
> closeStreams();
I can't find this one either. close()?
> socket.close();
> }
>}
>
>public class Main {
>
> public static void main(String[] args)
> {
> ClientGUI cg new ClientGUI("ChatClient");
> cg.setVisible(true);
> }
>
>}
>
>The server code is:
>
>
>import java.awt.*;
>import javax.swing.*;
>import java.awt.event.*;
>import java.io.*;
>import java.net.*;
>import java.util.*;
>
>public class ServerGUI extends JFrame implements Runnable
>{
> private JTextArea logArea;
> private JLabel logLabel;
> private JPanel logPanel;
>
> private ServerSocket ss;
> private Socket socket;
>
> private InputStream is;
> private OutputStream os;
>
> private PrintWriter toClient;
> private BufferedReader fromClient;
>
> static final int PORT_NUMBER 4000;
> static final String CLIENT_LOGGINGOFF "Exit";
>
> //constructor for the Server GUI
> public ServerGUI(String title)
> {
> setSize(400, 400);
> setTitle(title);
> setLocation(100, 100);
> logArea new JTextArea(15, 30);
> JScrollPane scr new JScrollPane(logArea);
> logLabel new JLabel("Logging history");
>
> logPanel new JPanel();
> logPanel.add(logLabel);
> logPanel.add(logArea);
>
> getContentPane().add(logPanel);
>
>
>
> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
> }
>
>//constructor for the server to set the socket to handle a new thread
> public ServerGUI(Socket s)
> {
> socket s;
> }
>
>
>
> public void run()
> {
> try
> {
> while(true)
> {
>
> openStreams();
> processClientRequests();
Is this supposed to be processRequests()?
> closeStreams();
> socket.close();
> }
> }
> catch(IOException e)
> {
> System.out.println("Trouble with a connection " + e);
> }
>
> }
>
> //helper method for the class to set up the streams
> private void open() throws IOException
> {
> final boolean AUTO_FLUSH true;
> is socket.getInputStream();
> fromClient new BufferedReader(new InputStreamReader(is));
> os socket.getOutputStream();
> toClient new PrintWriter(os, AUTO_FLUSH);
> }
>
>//process the string from received from each client
> private void processRequests() throws IOException
> {
> String userName;
> String reply;
> int numberOfFields 3;
> String [] fieldContents new String[numberOfFields];
> userName fromClient.readLine();
> while(!(userName.equals(CLIENT_LOGGINGOFF)))
> {
> StringTokenizer tokensIn new StringTokenizer(userName, " ");
> int i 0;
> while(tokensIn.hasMoreTokens())
> {
> fieldContents[i] tokensIn.nextToken();
> i++;
> }
>
> reply fieldContents[0];
> toClient.println(reply);
> logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
>"+fieldContents[2]+"\n");
> userName fromClient.readLine();
> }
> }
>
> //helper method to close the streams with each client
> private void close() throws IOException
> {
> toClient.close();
> os.close();
> fromClient.close();
> is.close();
> }
>}
>
>import java.net.*;
>import java.io.*;
You should move your imports inside the ChatHandler class.
>
>public class ChatHandler
>{
> static final int PORT_NUMBER 4000;
>
> public ChatHandler()
This inner class shouldn't be public.
> {
> }
>
> public void run()
> {
> try
> {
> ServerSocket server new ServerSocket(PORT_NUMBER);
> while(true)
> {
> Socket client server.accept ();
> System.out.println ("Accepted from " + client.getInetAddress ());
> Thread aThread new Thread(new ServerGUI(client));
> aThread.start ();
> }
> }
> catch(IOException e)
> {
> System.out.println("Trouble with ServerSocket, port
>"+PORT_NUMBER +": " + e);
> }
> }
>}
>
>
>public class Main {
Any particular reason you have your main method inside an inner class? You
need to put that right in the ServerGUI class.
>
> public static void main(String[] args)
> {
> ServerGUI sg new ServerGUI("ChatServer");
> sg.setVisible(true);
> ChatHandler cH new ChatHandler();
> cH.run();
> }
>
>}
>
>
>It is the first time I use threads and maybe there is something I dont
>understand. Can anyone point me to the right direction please? I think
>the problem may be with the 2 server constructor but I am not sure how
>to solve it.
>
>Cheers Pat
>
That's all I have for now, hope I wasn't too hard on ya.
|
| |
|
| |
 |
Max010

|
Posted: 2005-8-22 22:12:00 |
Top |
java-programmer >> Threads java.lang.NullPointerException
Hi Sean thanks for replying to my message and dont worry about being
hard on me. I am a bit slow with this topic bare with me. I ve made
some adjustment to my program and now it works but every time I run the
client and click on the connect button a new server GUI is started.
For every client GUI there is one server GUI. I would like to have
only one server GUI that displays all the user name that logged on to
the server how do I achieve that?
thanks Pat
//start of the main class
public class Main {
public static void main(String[] args)
{
HandleAClient hAc = new HandleAClient();
hAc.run();
}
}
//end of main class
//start of ServerGUI class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ServerGUI extends JFrame implements Runnable
{
private JTextArea logArea;
private JLabel logLabel;
private JPanel logPanel;
private ServerSocket ss;
private Socket socket;
private InputStream is;
private OutputStream os;
private PrintWriter toClient;
private BufferedReader fromClient;
static final int PORT_NUMBER = 4000;
static final String CLIENT_LOGGINGOFF = "Exit";
public ServerGUI(String title,Socket s)
{
socket = s;
setSize(400, 400);
setTitle(title);
setLocation(100, 100);
logArea = new JTextArea(15, 30);
JScrollPane scr = new JScrollPane(logArea);
logLabel = new JLabel("Logging history");
logPanel = new JPanel();
logPanel.add(logLabel);
logPanel.add(logArea);
getContentPane().add(logPanel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run()
{
try
{
while(true)
{
openStreams();
processClientRequests();
closeStreams();
socket.close();
}
}
catch(IOException e)
{
System.out.println("Trouble with a connection "+e);
}
}
private void openStreams() throws IOException
{
final boolean AUTO_FLUSH = true;
is = socket.getInputStream();
fromClient=new BufferedReader(new InputStreamReader(is));
os = socket.getOutputStream();
toClient = new PrintWriter(os, AUTO_FLUSH);
}
private void processClientRequests() throws IOException
{
String userName;
String reply;
int numberOfFields = 3;
String [] fieldContents = new String[numberOfFields];
userName = fromClient.readLine();
while(!(userName.equals(CLIENT_LOGGINGOFF)))
{
StringTokenizer tokensIn =new StringTokenizer(userName, "
");
int i = 0;
while(tokensIn.hasMoreTokens())
{
fieldContents[i] = tokensIn.nextToken();
i++;
}
reply = fieldContents[0];
toClient.println(reply);
logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
"+fieldContents[2]+"\n");
userName = fromClient.readLine();
}
}
private void closeStreams() throws IOException
{
toClient.close();
os.close();
fromClient.close();
is.close();
}
}
//end of class
//start of handle a client class
import java.io.*;
import java.net.*;
public class HandleAClient
{
static final int PORT_NUMBER = 4000;
public HandleAClient()
{
}
public void run()
{
try
{
ServerSocket ss = new ServerSocket(PORT_NUMBER);
while(true)
{
Socket client = ss.accept();
Thread session = new Thread(new ServerGUI("chatServer4",
client));
session.start();
}
}
catch(IOException e)
{
System.out.println("Trouble with ServerSocket , port
"+PORT_NUMBER +": " + e);
}
}
}
//end of class
|
| |
|
| |
 |
Andrew Thompson

|
Posted: 2005-8-22 22:48:00 |
Top |
java-programmer >> Threads java.lang.NullPointerException
On 22 Aug 2005 07:12:24 -0700, Max010 wrote:
> I would like to have
> only one server GUI that displays all the user name that logged on to
> the server how do I achieve that?
You might create a singleton instance of any application by
- reserving a socket and
- checking for it at start-up.
If the socket is reserved, simply bring the existing
application 'toFront()'.
HTH
--
Andrew Thompson
physci.org 1point1c.org javasaver.com lensescapes.com athompson.info
"As it is I'm climbing up an endless wall. No time at all."
The Police 'No Time This Time'
|
| |
|
| |
 |
Thomas Fritsch

|
Posted: 2005-8-23 7:51:00 |
Top |
java-programmer >> Threads java.lang.NullPointerException
"Max010" <email***@***.com> wrote:
> Hi there I was wondering if anyone can help me please.
>
> I ve been working on a simple chat server program and it works when the
> server handles one client at the time. I ve been trying to make the
> server able to answer clients requests at the same time with threads.
>
> I always get the same error message when I run the server:
>
> java.lang.NullPointerException
> at chatserverq3.ServerGUI.processClientRequests(ServerGUI.java:113)
> at chatserverq3.ServerGUI.run(ServerGUI.java:73)
> at java.lang.Thread.run(Thread.java:484)
You could get a lot of help from the exception stack trace above.
(*) The error occured in line 113 of ServerGUI.java in method
processClientRequests. Exactly which line is that? Unfortunately you
did't mark
this line in the code below. Without knowing this, I could guess, but
not help.
(*) The term "NullPointerException" tells,
that in that line 113 an expression on the left side of a "." was null.
>
[...]
> //process the string from received from each client
> private void processRequests() throws IOException
> {
> String userName;
> String reply;
> int numberOfFields = 3;
> String [] fieldContents = new String[numberOfFields];
> userName = fromClient.readLine();
> while(!(userName.equals(CLIENT_LOGGINGOFF)))
> {
> StringTokenizer tokensIn = new StringTokenizer(userName, " ");
> int i = 0;
> while(tokensIn.hasMoreTokens())
> {
> fieldContents[i] = tokensIn.nextToken();
> i++;
> }
>
> reply = fieldContents[0];
> toClient.println(reply);
> logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
> "+fieldContents[2]+"\n");
> userName = fromClient.readLine();
> }
> }
[...]
--
"TFritsch$t-online:de".replace(':','.').replace('$','@')
|
| |
|
| |
 |
Max010

|
Posted: 2005-8-24 3:47:00 |
Top |
java-programmer >> Threads java.lang.NullPointerException
Thanks Thomas but I ve been working on the program and now it works but
every time I launch the client frame a server frame comes up.
What I m trying to achieve is to launch several clients (no problem
with that) and only one server frame that record all the clients that
logged on and off.
Here is the server code:
//start of server class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ServerGUI extends JFrame implements Runnable
{
private JTextArea logArea;
private JLabel logLabel;
private JPanel logPanel;
private ServerSocket ss;
private Socket socket;
private InputStream is;
private OutputStream os;
private PrintWriter toClient;
private BufferedReader fromClient;
private ArrayList historyUser = new ArrayList();
static final int PORT_NUMBER = 4000;
static final String CLIENT_LOGGINGOFF = "Exit";
//I ve created a HandleAClient class that listen for client connections
and every time that one clients request a connection it creates a
thread using the ServerGUI constructor. Line 17 is what does that in
the HandleAClient class see below.
public ServerGUI(String title,Socket s)
{
socket = s;
setSize(400, 400);
setTitle(title);
setLocation(100, 100);
logArea = new JTextArea(15, 30);
JScrollPane scr = new JScrollPane(logArea);
logLabel = new JLabel("Logging history");
logPanel = new JPanel();
logPanel.add(logLabel);
logPanel.add(logArea);
getContentPane().add(logPanel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run()
{
try
{
while(true)
{
openStreams();
processClientRequests();
closeStreams();
socket.close();
}
}
catch(IOException e)
{
System.out.println("Trouble with a connection "+e);
}
}
private void openStreams() throws IOException
{
final boolean AUTO_FLUSH = true;
is = socket.getInputStream();
fromClient=new BufferedReader(new InputStreamReader(is));
os = socket.getOutputStream();
toClient = new PrintWriter(os, AUTO_FLUSH);
}
private synchronized void processClientRequests() throws IOException
{
String userName;
String reply;
int numberOfFields = 3;
String [] fieldContents = new String[numberOfFields];
userName = fromClient.readLine();
while(!(userName.equals(CLIENT_LOGGINGOFF)))
{
StringTokenizer tokensIn =new StringTokenizer(userName, "
");
int i = 0;
while(tokensIn.hasMoreTokens())
{
fieldContents[i] = tokensIn.nextToken();
i++;
}
reply = fieldContents[0];
addUserToList(reply);
toClient.println(broadcast().toString());
logArea.append("[ " + reply + " ] "+ fieldContents[1]+"
"+fieldContents[2]+"\n");
userName = fromClient.readLine();
}
}
private synchronized void addUserToList(String aUser)
{
while(historyUser.size()>= 0)
{
try
{
wait();
}
catch (InterruptedException e)
{
String errMessage = e.getMessage();
System.out.println("Error "+ errMessage);
}
historyUser.add(aUser);
notifyAll();
System.out.println(aUser);
}
}
private synchronized ArrayList broadcast()
{
ArrayList usersLogged = new ArrayList();
Iterator listIt = historyUser.iterator();
while(listIt.hasNext())
{
usersLogged.add(listIt.next());
}
return usersLogged;
}
private void closeStreams() throws IOException
{
toClient.close();
os.close();
fromClient.close();
is.close();
}
}
//end of server class
//start of HandleAClient class
import java.io.*;
import java.net.*;
public class HandleAClient
{
static final int PORT_NUMBER = 4000;
public HandleAClient()
{
}
public void run()
{
try
{
ServerSocket ss = new ServerSocket(PORT_NUMBER);
while(true)
{
Socket client = ss.accept();
//line 17 Thread session = new Thread(new
ServerGUI("chatServer4", client));
//unfortunately every time the ServerGUI constructor is called a new
frame appears. How can I create a thread to handle a client without
creating a server frame??? Maybe I m doing it all wrong and there s
another strategy I could follow up any suggestion please?
session.start();
}
}
catch(IOException e)
{
System.out.println("Trouble with ServerSocket , port
"+PORT_NUMBER +": " + e);
}
}
}
Regards Pat
|
| |
|
| |
 |
Roedy Green

|
Posted: 2005-8-30 8:03:00 |
Top |
java-programmer >> Threads java.lang.NullPointerException
On 23 Aug 2005 12:47:18 -0700, "Max010" <email***@***.com> wrote
or quoted :
>Thanks Thomas but I ve been working on the program and now it works but
>every time I launch the client frame a server frame comes up.
Listening with one ear, it looks like you need to strip out the GUI
stuff from your server class to create an InvisibleServer, then extend
it to create a VisibleServer then spawn your extra threads as
InvisibleServers.
--
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- Writing to a file... I have a program that has the following method to save data to a text
file:
private static File mUserFile = null;
private static String mUserSolutions = "C:/solutions/User_solutions.txt";
public void saveSolution(String pGameBoard, String pSolution, char pLevel) {
if (mUserFile == null)
mUserFile = new File(mUserSolutions);
try {
PrintWriter printWriter = null;
if (!mUserFile.exists()) {
printWriter = new PrintWriter(new
FileOutputStream(mUserFile));
} else {
printWriter = new PrintWriter(new FileOutputStream(mUserFile,
true));
}
Solution solution = new Solution(pGameBoard, pSolution, pLevel);
saveSolution(solution);
printWriter.println(pLevel + ":" + pGameBoard + ":" + pSolution);
printWriter.flush();
printWriter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
saveSolution(solution) just saves the object to an internal table.
When I execute this code in Eclipse, it will create or append to my file
like I expect but when I create an executable jar file and run it, the
screen says that it performed the save but there isn't any file created and
if I create the file manually, it doesn't append to it. Any help would be
greatly appreciated.
- 2
- cup dilemmaHi all,
I'm making a parser with java_cup and jlex, it must recognize a language
like this:
// Definition of the apparel heads:
dress = [quality->10, woven->8];
shirt = [quality->10, woven->8];
?
// Description of the apparel heads:
BOSSdress = quality *, woven -: dress;
dressofValentino = quality *, woven +: dress;
shirtofArmani = quality +, woven +: shirt;
The definition of the apparel heads is made with this cup code:
non terminal frasi, frase;
frasi ::= frasi frase | frase;
frase ::= LETTER:var EQ QO LETTER:attr ARROW NUMBER:n QC SEMI
{:
System.out.print("Ist: " + var);
System.out.print(" attrib: " + attr);
System.out.println(" value: " + n);
:};
Now I need recognize the second part of language, but how I can
distinguish by the '?' ?
JLex code:
%%
%cup
%%
";" { return new Symbol(sym.SEMI); }
"=" { return new Symbol(sym.EQ); }
"->" { return new Symbol(sym.ARROW); }
"[" { return new Symbol(sym.QO); }
"]" { return new Symbol(sym.QC); }
"?" { return new Symbol(sym.ASKP); }
[0-9]+ { return new Symbol(sym.NUMBER, new Integer(yytext())); }
[a-zA-Z]+ { return new Symbol(sym.LETTER, new String(yytext())); }
[ \t\r\n\f] { /* ignore white space. */ }
. { System.err.println("Illegal character: "+yytext()); }
Thanks in advance
- 3
- CVS Resource History Date/Time is not availableSince the beginning of the new year, when I do a Show In Resource
History for any resource in CVS, it displays revision, tag, and other
information as normal; however, the Date field it displays "Not
Available". Does anyone know why? I am using Eclipse version 3.1.0
Many Thanks.
- 4
- Cannot delete Se Development Kit from VistaHello,
I need to reinstall the JDK but the installer insists the development kit is
still installed, when I agree to re-installing it just stays in an endless
loop of telling me it is already installed and do I want to reinstall. I
have physically deleted all the java directories and last night paid 40
bucks for a registry cleaner that has made no difference.
When I try to delete using the uninstall utility in Vista it claims to
delete it by the Java SE Development Kit Update 2 reference stays there.
Does anyone know what I need to do to be able to get it re-installed?
Thanks,
Wayne
- 5
- Using relative path in java programs - how ?Hi
I wrote a new servlet that uses a configuration file to store
parameters.
The problem is that I want to use a relative path when accessing this
file, since I dont know where this servlet will be deployed.
Basically, I want it to be in the same directory where the .class
files are located.
Using the property user.dir does'nt help because it returns the
server's executable path.
How can I control this ? how can the program "know" where the class
files are ?
- 6
- getParameterMetaData() throwing UnsupportedOperationException?Hi all,
Pls tell me why getParameterMetaData() of PreparedStatement is
throwing java.lang.UnsupportedOperationException
(pls see below code)
i guess the jdbc driver does not implement the method? is it correct?
Is it a problem with MS Access database?
Is there any solution to this?
Any comments are highly appreciated,
Regards,
Dhanan
code snippet: ..............
..............
String DEFAULT_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
String DEFAULT_URL = "jdbc:odbc:DRIVER={Microsoft Access
Driver (*.mdb)};DBQ=c:\\db1.mdb";
Class.forName(DEFAULT_DRIVER);
Connection con =
DriverManager.getConnection(DEFAULT_URL,"test","testpwd");
PreparedStatement ps = con.prepareStatement("Select * from Table1
where f1 = ? and f2 = ?");
ps.setString(1, "test");
ps.setString(2, "test");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
System.out.println(b);
}
System.out.println("Before getParameterMetaData()");
ParameterMetaData pmtdata = ps.getParameterMetaData();
System.out.println("Before getParameterCount");
System.out.println("Param count: " + pmtdata.getParameterCount());
rs.close();
cst.close();
con.close();
.............
.............
Stack trace:
java.lang.UnsupportedOperationException
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.getParameterMetaData(JdbcOdbcPreparedStatement.java:3446)
- 7
- Applet scanning another IP!Hi, i'm trying to scan from an applet other IP then the Server IP. But
i know that this is a restriction of the applet, because i can scan
only the Server IP. is there a methods to force this?
- 8
- Signing applet jar without verified digital IDI'm the admin of an open-source java project
(http://jugglinglab.sourceforge.net), and a rank newbie to the topic
of jar signing. I would like to be able to copy/paste text between my
applet and other applications, and from what I understand this
requires the applet to be trusted.
Now a verified digital ID from VeriSign seems to cost around $400,
which is way too much for an open-source project to consider. I'm
wondering if it's possible to create our own (unverified) ID and
self-signed certificate, and sign our jar with that. I have hunted
around and not seen any straightforward instructions on how to do
this, or even an indication of whether it's possible.
Can anyone clue me in here? Thanks for the help!
Jack
- 9
- Java Compilers... I need get some good compiler but its hard 2 find it...So can some 1
give me link or good
compiler for java..
well I think google is my best friend.
email***@***.com
- 10
- JNI string problemI have a JNI problem when calling native code from a java program. The
java program is passing in a non-empty String to the native code, but at
the native code level I crash out on a call to NewStringUTFChars using
the passed-in jstring. When I run with the -Xcheck:jni parameter, I get
the following output:
JVMCI161: FATAL ERROR in native method: JNI received a null string
at a.b.c.MyNativeMethod(Native Method)
(class + package names obscured)
So, it would appear that the jstring getting passed in is null in some
way. Question is, how can I examine this jstring object to see what's in
it? I've tried to find the definition of jstring without luck. Can
anyone help here?
thanks
alex
- 11
- Servlet Compiler Error.I need some help/assistance from one of you able people for always getting a
compiler error indicating that the line[s] "private StringBuffer
getConfigTable(ServletConfig config) {" AND the line "private StringBuffer
getContextTable(ServletContext context) {" are illegal starts of the
expression! I have tried to do some "workarounds" for this problem but I am
still getting that compiler error. Can anyone please help me with this?
(There MIGHT be one too many ending "}" 's at the bottom of the file, but
other than that what is the problem?
/* Well here I go again with tryin' my hand at creating a new servlet.
Incidentally, this particular servlet will be called the
*"ContainerServlet.java".
*/
package org.steve.burroughs;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class ContainerServlet extends GenericServlet {
public void service( ServletRequest request, ServletResponse response)
throws
ServletException, IOException {
StringBuffer configTable = getConfigTable(getServletConfig() ) ;
StringBuffer contextTable = getContextTable(getServletContext() ) ;
response.setContentType( "text/html" );
PrintWriter steve = response.getWriter();
steve.println("<html><head><title>Why Can\'t I Get "+
"Screwed??</title><head><body>");
steve.println("<h1>Servlet Configuration Information</h1>" +
configTable + "<hr>");
steve.println("<h1>Servlet Context Information</h1>" +
contextTable);
steve.println("</body></html>");
steve.flush();
steve.close();
private StringBuffer getConfigTable(ServletConfig config) {
HTMLTable table = new HTMLTable ();
table.appendRow("Servlet Name", config.getServletName( ));
Enumeration e = config.getInitParameterNames() ;
while ( e.hasMoreElements() ) {
String pn = (String)e.nextElement();
String pv = config.getInitParameter(pn);
table.appendRow("Parameter : <code> " + pn +
"</code>", pv);
}
return table.toStringBuffer();
}
private StringBuffer getContextTable(ServletContext context) {
HTMLTable table = new HTMLTable ();
table.appendTitleRow("Attributes") ;
Enumeration e = context.getAttributeNames() ;
while ( e.hasMoreElements() ) {
String pn = (String)e.nextElement ();
Object po = context.getAttribute( pn);
String pv = " " ;
if( po instanceof String) {
pv = (String) context.getAttribute( pn);
} else if ( po instanceof String[]) {
String[] pa = (String[])context.getAttribute( pn);
for(int i = 0; i < pa.length; i++){
pv = pv + pa[i] + "<br>";
}
}
else {
pv = context.getAttribute( pn).toString();
}
table.appendRow("Attribute : <code> " + pn +
"</code>", pv);
}
}
}
}
- 12
- eclipse exporting project having extarnal jars as libsHi there
i have done a java project on eclipse , i have used some extarnal jar
files as lib in my project added them by (right click on my project
folder --> properties --> java build path --> libraries --> add
external jars) i also checked on them in
(right click on my project folder --> properties --> java build path
--> order and export)
but when i export my project to executable jar file ( i get the file)
but cant run it
on double click it says (could not find main class) while i have
defined the correct main class in the exporting wizard,
i also tried to extract the jar file and didnt found any of my external
jar libs in it so how can i give this file to my users without making
them download the libs themselves
i need your help please
- 13
- 14
- 15
- Great SWT Programemail***@***.com wrote:
> On Oct 15, 7:04 pm, email***@***.com (Bent C Dalager) wrote:
>> In article <email***@***.com>,
>> I have explained this earlier. I do not care to do so again.
>
> I don't care for your tone, mister.
>> I will argue with whomever I please.
>
> Then you will face the consequences.
Why is it that I am thinking of the saying: "Empty barrels
make most noise" ?
:-)
Arne
|
|
|