| Looking for HTML Renderer |
|
 |
Index ‹ java-programmer
|
- Previous
- 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
- 2
- 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
- 3
- Column numbers is stack trace - enhancement requestI filed the following enhancement request to Sun. Would like to hear
opinion about how useful implementing this feature would be.
Synopsis: Need column numbers in stack traces
Description:
A DESCRIPTION OF THE REQUEST :
Stack traces contain only line numbers and in certain cases line number
alone is not sufficient for figuring out where exactly an exception
occurred. Consider the following line of code.
value = getItem().getRelatedItem().getName().getValue();
If the above line throws a NullPointerException, we have no clue
whether it is the getItem, getRelatedItem or the getName that is
returning a null value. So providing just the line number is not
sufficiently helpful in narrowing down the problem. If the stack trace
also contains the column number where the null was encountered, it will
be really helpful.
Though the above code could be rewritten to several lines so that we
can clearly identify which method returned null, there are tons of such
existing code and changing them all will be an unreasonably complex
task.
- 3
- 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 :
- 6
- 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
- 6
- 7
- 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
- 7
- 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.
- 7
- 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
- 7
- 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!
- 7
- 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
- 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
- 7
- 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
- 11
- JDK 1.4.2_05I use WebLogic 8.1 on a Solaris 9 box with 8 processors. I have JDK
1.4.2_05 installed and due to long pauses with the default collector, I
tried out the Concurrent garbage collector. However, once I do that,
the system runs out of file handles within minutes of starting the load
test. Solaris is setup with 8192 as the top limit for file handles.
I tried various options within Concurrent garbage collector (like
ParNewGC, CMSParallelRemark) but all lead to system running out of file
handles.
Any inputs ?
Thanks,
Kevin.
- 13
- 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
|
| Author |
Message |
Xiaolei Li

|
Posted: 2004-10-7 6:24:00 |
Top |
java-programmer, Looking for HTML Renderer
hi,
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
|
| |
|
| |
 |
Andrew Thompson

|
Posted: 2004-10-7 6:33:00 |
Top |
java-programmer >> Looking for HTML Renderer
On Wed, 6 Oct 2004 22:23:59 +0000 (UTC), Xiaolei Li wrote:
> 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 ...
Why do you want to know the physical location?
It is just that each browser will probably render a page
slightly differently, so what is the point or end purpose
of knowing the physical location of an UI element in a
web-page as rendered by that particular browser?
What do you want to achieve as the end result?
--
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.lensescapes.com/ Images that escape the mundane
|
| |
|
| |
 |
Xiaolei Li

|
Posted: 2004-10-7 9:28:00 |
Top |
java-programmer >> Looking for HTML Renderer
Andrew Thompson <email***@***.com> wrote:
> On Wed, 6 Oct 2004 22:23:59 +0000 (UTC), Xiaolei Li wrote:
>
>> 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 ...
>
> Why do you want to know the physical location?
>
> It is just that each browser will probably render a page
> slightly differently, so what is the point or end purpose
> of knowing the physical location of an UI element in a
> web-page as rendered by that particular browser?
>
> What do you want to achieve as the end result?
the algorithm constructs blocks out of the page based on visual cues.
see the algorithm here: http://www.cen.uiuc.edu/~dengcai2/VIPS/VIPS.html
basically, it's vision-based partitioning of the webpage. more
intuitive than a simple DOM tree.
anyway, i think the slight differences between browsers won't matter too
much. any competent renderer will do.
--
Xiaolei Li | email***@***.com | www.xiaolei.org
|
| |
|
| |
 |
bugbear

|
Posted: 2004-10-7 20:04:00 |
Top |
java-programmer >> Looking for HTML Renderer
Xiaolei Li wrote:
> Andrew Thompson <email***@***.com> wrote:
>
>>On Wed, 6 Oct 2004 22:23:59 +0000 (UTC), Xiaolei Li wrote:
>>
>
> anyway, i think the slight differences between browsers won't matter too
> much. any competent renderer will do.
>
<speculation>
IIRC Sun had a native java Browser.
If this is open source, you may be able
to exploit the renderer.
</speculation>
BugBear
|
| |
|
| |
 |
Andrew Thompson

|
Posted: 2004-10-7 20:46:00 |
Top |
java-programmer >> Looking for HTML Renderer
On Thu, 07 Oct 2004 13:04:05 +0100, bugbear wrote:
> Xiaolei Li wrote:
..
>> anyway, i think the slight differences between browsers won't matter too
>> much. any competent renderer will do.
..
> IIRC Sun had a native ..
'native' to what?
>..java Browser.
This one?
<http://java.sun.com/products/archive/hotjava/index.html>
> If this is open source, you may be able
> to exploit the renderer.
As I understand it is based upon JEditorPane(/JEditorPain).
Can anyone confirm?
--
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.lensescapes.com/ Images that escape the mundane
|
| |
|
| |
 |
Thomas Weidenfeller

|
Posted: 2004-10-8 0:47:00 |
Top |
java-programmer >> Looking for HTML Renderer
bugbear wrote:
> IIRC Sun had a native java Browser.
Yes, it was called HotJava.
> If this is open source, you may be able
> to exploit the renderer.
Parts of it became the HTML parser in Swing. This parser-related
comp.lang.java.gui FAQ (v1.13) questions:
6.3 Styled Text / JEditorPane / JTextPane
Q6.3.1 Can I use RTFEditorKit to read RTF documents created by Word?
Q6.3.2 I have problems using the Swing HTML parser to parse all
kinds of HTML. Is this normal?
Q6.3.3 Some of my CSS styles don't work out. Is this normal?
Q6.3.4 Can I use Swing's HTML support to write a web browser?
Q6.3.5 Can I use Swing's HTML support to build an on-line
help system or e-book?
Q6.3.6 If HTML support is really so broken in Java, what is it
good for?
/Thomas
|
| |
|
| |
 |
Thomas Weidenfeller

|
Posted: 2004-10-8 0:49:00 |
Top |
java-programmer >> Looking for HTML Renderer
Andrew Thompson wrote:
> As I understand it is based upon JEditorPane(/JEditorPain).
> Can anyone confirm?
It's the other way around. The HotJava remains were recycled in Swing.
This is the reason why you suddenly see "documents" for this components,
instead of "models".
/Thomas
|
| |
|
| |
 |
Xiaolei Li

|
Posted: 2004-10-8 3:15:00 |
Top |
java-programmer >> Looking for HTML Renderer
Thomas Weidenfeller <email***@***.com> wrote:
> bugbear wrote:
>> IIRC Sun had a native java Browser.
>
> Yes, it was called HotJava.
>
> Parts of it became the HTML parser in Swing. This parser-related
> comp.lang.java.gui FAQ (v1.13) questions:
>
> Q6.3.2 I have problems using the Swing HTML parser to parse all kinds
> of HTML. Is this normal?
> Q6.3.3 Some of my CSS styles don't work out. Is this normal?
> Q6.3.6 If HTML support is really so broken in Java, what is it good
> for?
From the answers in the FAQ, the Swing HTML parser seems old and broken
(for real world purposes). So back to my original question, is there
anything out there that'll do what I want (render and relate to a DOM
tree)? I've looked at NekoHTML/JTidy/Xerces. It was easy to have them
build a DOM document for a HTML page. But they don't have any rendering
component. JRex *seems* like it has what I want but I haven't had time
to mess with it.
Thanks.
--
Xiaolei Li | email***@***.com | www.xiaolei.org
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- 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
- 2
- 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.
- 3
- 4
- 5
- 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
- 6
- 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
- 7
- 8
- 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)
- 9
- Threads java.lang.NullPointerExceptionHi 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
- 10
- 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 ?
- 11
- 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.
- 12
- 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
- 13
- 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);
}
}
}
}
- 14
- 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?
- 15
- 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
|
|
|