 |
 |
Index ‹ java-programmer
|
- Previous
- 1
- RPN CalculatorI've searched the web for a couple of hours for a calculator with this
requirements
It has to
0) be free to download and use
1) be able of RPN
2) be able to run in a standalone window (i.e. not in a web browser)
3) be written in java
4) preferably be open source
Someone who can give me a hint???
- 1
- class data sharing subjective test resultsHi all,
I made some tests with the new "Class Data Sharing" function
provided by the JVM (since version 1.5.0 / 5.0) and decided
to share my class data sharing discoveries with the group
(this topic is not often discussed here).
The tests were made on an Un*x system (Linux Fedora Core 3).
First of all, the performance gain is very real, especially
when launching lots of small apps.
Basically, it comes down to using the parameter/value
"-Xshare:off", "-Xshare:on" or "-Xshare:auto" (which is
the default) when calling the JVM.
The command line: "java -Xshare:dump" can be used to
force the creation of the memory-mapped archive file
(the shared classes). (btw this step is apparently
necessary on some Un*x systems!?. My system would
/not/ default to using the sharing, I had to
-Xshare:dump once and then add -Xshare:on to force my
application sharing the classes.)
I had some "text file utilities" I wrote in Java which I'm
used to call from the command line (or from shell scripts).
This is clearly one area where the JVM's startup time
is a problem. I noticed gain of about 30% in this case
(using a non-scientific approach repeated many case, with
and without CDS).
If the JVM is installed in userland, each user will have his
own "cached" file (classes.jsa, about 11 Mb on my machine).
If only one JVM is installed for all the users, all the
users will share the same classes.jsa file (JSA for "Java
Shared Archive").
It may be possible to force different identical JVM
installed in different userland to use the same classes.jsa
but I didn't try to do this (simply copying the classes.jsa
file from one user on top of the classes.jsa file of another
user doesn't work, although the files have the same
length [but different checksums]).
I was pleasingly surprised by those first results and I
decided to force all my apps to use the JVM 1.5.0 and its
class data sharing feature, including IntelliJ IDEA (which
comes with its own JRE and refuse to run with an 1.5 JRE
without some hacking).
After days of "switching" to an 1.5 JVM and forcing all my
apps to use class data sharing, I can tell that overall
everything "Java related" is a little bit more responsive.
It is particularly noticeable when calling Java utilities
from the command line (which is no surprise) but also when
running unit tests (I tend to launch my test(s) quite often).
The memory footprint is also reduced compared to 1.4.2
(when running several apps).
I'm curious about your results too :)
See you all very soon (and "hi" to the c.l.j.p. regular
I met on freenode's #java saturday ;),
Jean
P.S : If I understood correctly, Apple made their
own class data sharing "hack" for Java (way before 1.5)
and Sun basically copied their "idea". Whatever... This
means that developers using MacOS X benefits automagically
from "class sharing" since quite some time and have
nothing particular to do in order to use it.
- 3
- Array reference in for loopI have a validate method in a bean class that works and now I want to
condense it into a for loop.
Here is what I have:
//firstname and lastname are declared earlier
public boolean validate()
{
boolean allOk=true;
if (firstName.equals("")) {
errors.put("firstName","Please enter your first name");
allOk=false;
}
if (lastName.equals("")) {
errors.put("lastName","Please enter your last name");
allOk=false;
}
return allOk;
}
My attempt doesnt work because I cant seem to figure out how to put
the array reference in the key part of the errors.put method:
public boolean validate()
{
boolean allOk=true;
String [] myarray = {firstname, lastname}
for(int i=0;i < myarray.length;i++)
{
if (myarray[i].equals("")) {
errors.put(myarray[i],"Please enter your " + myarray[i]);
allOk=false;
}
}
return allOk;
}
The results dont validate any of my data so I assume I have something
wrong with my array. Please advise.
- 8
- Bug or featureHi, can someone explain the behaviour of that snip
public class Test
{
public static void main(String[] args)
{
try
{
Class c = Class.forName("BUG");
}
catch (ClassNotFoundException e)
{
}
System.out.println("Everything works?");
try
{
Class c = Class.forName("NotbUg");
}
catch (ClassNotFoundException e)
{
}
System.out.println("Still works?");
try
{
Class c = Class.forName("bUg");
}
catch (ClassNotFoundException e)
{
}
System.out.println("Everything works!!");
}
}
class BUG
{
}
In not works on JDK 1.4.2 but JDK 1.1.4. Bug or feature that question is.
Thanks in advance.
Serge
- 8
- Is there a startup banner class?Hello,
I have an application to which I would like to add a startup banner.
Much like other applications that display this banner while performing
a somewhat lenghty (by computing standards) process in the background,
I have the same need.
Is there a class that supplies the panel (banner) and methods to
determine when the background process has completed?
Thanks in advance,
Todd
- 9
- CloneableWould have been possible to some how redefine Cloneable so that clone
did not return an object but rather at object of the type implementing
clone?
--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm
Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
- 10
- How to get connection to remote hostHi all,
I am beginner in httpunit i am trying to get resonse from a remote
host, but i am not able to get it
the error is
connnection Exception: connection refused; connect
how can i resolve it
thanks and regards,
Arun
- 10
- Induction question, help needed.Help needed on this question. Any help is appreciated. Thanks in
advance.
Given a binary string (i.e. a finite sequence of 0's and 1's) we
choose any two digit substring 01 and replace it by a string of the
form 100...0 using an arbitrary (but finite) number of zeros. Prove
by induction that this transformation can not be performed infinitely
many times, i.e. this sequence of transformations must terminate for
any input string.
- 10
- JDialog (or any window) sizingI would like my JDialog to pop up with a size that is just adequate to
contain what is within, which includes various components and layouts in
the hierarchy. I'm hoping someone can tell me in a nutshell what
sequence of operations to perform.
- 12
- Problem with update Manager in eclipseHi
I have been trying to access the eclipse update site.
Unfortunately when I go on the newly created eclipse item
in the feature updates pane things seem to stop. A
message
Connecting... Connecting to
"http://update.eclipse.org/updates"
appears but nothing happens and the screen kind of hangs
until i press the red button (cancel current operation
option). I work from behind a proxy. I did the
appropriate settings in the preferences (entering the proxy name and
port). I expect to be asked for my username and password and
subsequently
be shown the builds. But nothing seems to be
happening.
But if I go to the eclipse item, right click and in
the properties select "website" instead of the "update
site" everything seems to work fine....as in i access the site
(updates still missing)
What is the reason of this behavior could i be doing
something wrong? I am new to eclipse....could anybody please help.
regards
- 14
- "this" statement?The "this" statement that is used in the method "exitRoom" and "explore" is
that synonymous with an "Explorer" object?
public class Explorer implements PlayerBehavior {
private String my_name;
private String my_secret_word;
private RoomBehavior where_I_am_now;
public Explorer(String name, String word){
my_name = name;
my_secret_word = word;
where_I_am_now = null;
}
public String speak(){
return my_secret_word; }
public void exitRoom(){
if ( where_I_am_now != null )
{ where_I_am_now.exit(this);
where_I_am_now = null;
}
}
public boolean explore(RoomBehavior r){
if ( where_I_am_now != null )
{ exitRoom(); }
boolean went_inside = r.enter(this);
if ( went_inside )
{ where_I_am_now = r; }
return went_inside;
}
public RoomBehavior locationOf(){
return where_I_am_now; }
}
- 14
- What happensHi,
Am a newbie to CORBA. What happens when a CORBA object is destroyed? I
heard that its ORB reference becomes invalid? If this' true, what
exactly is meant by 'invalid'? What if I try to refer the object after
it is destroyed? And also how do I come to know if the object is
destroyed?
Thanks.
- 14
- build failure on yesterday's -currentHi,
Following the threading, gcc, and symbol changes, I removed /usr/local
and /usr/X11R6 and am building everything from scratch.
jdk15 failed with:
bad class file: /usr/ports/java/jdk15/work/control/build/bsd-i586/gensrc/java/nio/channels/AsynchronousCloseException.java
file does not contain class java.nio.channels.AsynchronousCloseException
Please remove or make sure it appears in the correct subdirectory of the classpath.
throws AsynchronousCloseException
^
Note: * uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
2 errors
gmake[7]: *** [.compile.classlist] Error 1
gmake[7]: Leaving directory `/usr/ports/java/jdk15/work/j2se/make/sun/javac/recompile/library'
gmake[6]: *** [optimized] Error 2
gmake[6]: Leaving directory `/usr/ports/java/jdk15/work/j2se/make/sun/javac/recompile/library'
gmake[5]: *** [all] Error 1
gmake[5]: Leaving directory `/usr/ports/java/jdk15/work/j2se/make/sun/javac/recompile'
gmake[4]: *** [all] Error 1
gmake[4]: Leaving directory `/usr/ports/java/jdk15/work/j2se/make/sun/javac'
gmake[3]: *** [all] Error 2
gmake[3]: Leaving directory `/usr/ports/java/jdk15/work/j2se/make/java/javac'
gmake[2]: *** [all] Error 1
gmake[2]: Leaving directory `/usr/ports/java/jdk15/work/j2se/make/java'
gmake[1]: *** [all] Error 1
gmake[1]: Leaving directory `/usr/ports/java/jdk15/work/j2se/make'
gmake: *** [j2se-build] Error 2
*** Error code 2
Stop in /usr/ports/java/jdk15.
*** Error code 1
Stop in /usr/ports/java/jdk15.
stretchlimo/usr/ports/java/jdk15;
This might be known already, but I didn't see a posting on this yet.
If you already know, I'm patient and will wait for a fix.
Thanks,
==ml
--
Michael W. Lucas email***@***.com, email***@***.com
http://www.BlackHelicopters.org/~mwlucas/
Coming Soon: "Absolute FreeBSD" -- http://www.AbsoluteFreeBSD.com
On 5/4/2007, the TSA kept 3 pairs of my soiled undies "for security reasons."
- 16
- Open Source Document Management in JavaHas anybody tried "Corendal DocSide" from http://www.corendal.com ? It
looks like a pretty clean electronic document management application.
Any experience with this tool ? (demo at
http://www.corendal.com/java-corendal/docside/home/)
- 16
- color palletI'm coding up a routine to dispaly a stacked bar graph using
Graphics2D. Each bar is made by a bunch of rectangles representing
each contributor. The color of each contributor should be different.
I need a way to assign these colors. The number of contributors can
change at runtime. Sequential colors should be well differentiated.
Does anyone have any suggestions for accomplishing this? I'd rather
not make the user specify colors at runtime.
Thanks,
Rob
|
| Author |
Message |
pickle

|
Posted: 2005-6-11 14:41:00 |
Top |
java-programmer, Hashtable q
When traversing an Enumeration of Hashtable keys, I know that modifying the
HT can cause problems. But is doing lookups okay? E.g., in the following
code:
<assume ht is a reference to a Hashtable object>
Enumeration e = ht.keys();
Object o;
while(e.hasmore()) {
o = e.next();
System.out.println(o + ": " + ht.get(o));
}
Is this guaranteed to print out all of the key-value pairs?
|
| |
|
| |
 |
Oliver Wong

|
Posted: 2005-8-13 4:49:00 |
Top |
java-programmer >> Hashtable q
"pickle" <email***@***.com> wrote in message
news:Y1wqe.13506$email***@***.com...
> When traversing an Enumeration of Hashtable keys, I know that modifying
> the
> HT can cause problems. But is doing lookups okay? E.g., in the following
> code:
>
> <assume ht is a reference to a Hashtable object>
> Enumeration e = ht.keys();
> Object o;
> while(e.hasmore()) {
> o = e.next();
> System.out.println(o + ": " + ht.get(o));
> }
>
> Is this guaranteed to print out all of the key-value pairs?
I won't use the word "guarantee" (what if a gamma ray from a distant
supernova explosion flies through your computer case, randomly scrambling
the bits in RAM?), but I think this is pretty safe.
- Oliver
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- "NullPointerException". (was Re: ArrayOutOfbounds, how come?)Mark Haase wrote:
>
> What exception, exactly?? Your subject says
> "ArrayOutOfBounds" but the catch block is
> "NullPointerException".
you got it right. it is indeed "NullPointerException".
mea culpa.
> You shouldn't be getting ArrayOutOfBoundsException, but
> your code will generate a NPE everytime because of a
> noobie mistake that you're making.
what is noobie?
> Below, you initialize a new array of JButton references,
> but each reference is still null.
>
>> button = new JButton[8][14];
>
> You need to put an object in each one of them before you
> start making calls like:
>
>
>> button[gridY1][gridX1].setText(button_text);
>
> How can you call setText on an object that doesn't exist?
> You can't. The runtime lets you know by throwing NPE.
>
> Do this:
>
> for (int i=0; i<8; i++)
> for (int j=0; j<14; j++)
> button[i][j] = new JButton();
>
> In the future, be more specific when you say "I have an
> error!! help!"..Name the exact error.
done.
no way. After changing to the following, it compiled pretty
well, but is still giving npe at = line.
-------------
JButton[][] button;
-----------------
for (int gridY1 = 0; gridY1 < d_rows; gridY1++) {
for (int gridX1 = 0; gridX1 < d_columns;
gridX1++) {
button[gridY1][gridX1] = new JButton();
}
}
-------------
when I changed the above block according to what was
suggested by Mr John in another thread of Mr Mike:
-------------
JButton[][] button = new JButton[d_rows][d_columns];
for (int gridY1 = 0; gridY1 < d_rows; gridY1++) {
for (int gridX1 = 0; gridX1 < d_columns;
gridX1++) {
button[gridY1][gridX1] = new JButton();
}
}
-------------
it again got compiled flawlessly, but I got npe at a further
line where I am refering a button for the first time:
------------
button[gridY1][gridX1].setText(button_text);
------------
what next?
-rawat
- 2
- Swing - how to catch all eventsProgramming in java for a while now, but I still have this silly
problem that I don't know if the experts has a simple answer.
I have a Swing app. Yes, simple stuff eh. Next, user logins to use
the app. If they don't do anything (mouse move, key press) for a
while, then I log out. The think is that detecting a mouse event, I
have to register with each of the tabpane of the app. I don't like
that. Also, I have to register with each components within the panel.
The same for keyboard. For keyboard, it seems I can register event
for just any component (with appropriate modifer to get the input map
and action map). However, I still have to register all keys which are
alot. I want the ability to catch the event from top down. Anyevent
would goes through my filters first. Would this be possible? How do
I solve this simple and common problem? Thank you very much in
advance.
- 3
- what needed for j2me
hi all, I'm starting developing stuff for siemens c55, but for starting
I'd like to know what do I need to have to develop...
I've got j2dsk1.4.2 but when I call javax it says it doesn't exist...
what do I need to have in order to get my laptop undergoing on cell
phone SW????
nuno silva
- 4
- how to map from display metrics to physical metrics...Suppose I have a screen which is 1024x768, how can I map this rectangle in
pixels into physical world dimensions in meters or in inches? Actually I
want to know the physical size of the viewable area of the monitor...
Please help me...
- 5
- UIDefaults.getUI() failed for JInternalFrame$JDesktopIconI am using a particular Look and Feel, and a class derived from
JInternalFrame. Whenever the JInternalFrame class is invoked, it generated
an exception (please see stack trace at the bottom of this message).
I know that to correct this exception, I must do something along the lines
of the following:
UIManager.put(XXX, YYY);// Where XXX is the String used to identify the
JInternalFrame$JDesktopIcon's UIand YYY the ui class for it.
However, I do not know how to go about discerning the values for XXX and
YYY. How can I find those out? I have tried:
UIManager.getLookAndFeelDefaults().put("ClassLoader",
getClass().getClassLoader());
UIManager.put("JDesktopIcon",
javax.swing.JInternalFrame.JDesktopIcon.class.getName());
UIManager.put("JInternalFrame",
javax.swing.JInternalFrame.class.getName());
updateUI();
With no luck at al. Can someone please help me to find out what parameters I
need to pass here? Thanks, Ike
--------stack trace-----------------------
UIDefaults.getUI() failed: no ComponentUI class for:
javax.swing.JInternalFrame$JDesktopIcon[,0,0,0x0,invalid,hidden,alignmentX=0
.0,alignmentY=0.0,border=,flags=0,maximumSize=,minimumSize=,preferredSize=]
java.lang.Error
at javax.swing.UIDefaults.getUIError(Unknown Source)
at javax.swing.MultiUIDefaults.getUIError(Unknown Source)
at javax.swing.UIDefaults.getUI(Unknown Source)
at javax.swing.UIManager.getUI(Unknown Source)
at javax.swing.JInternalFrame$JDesktopIcon.updateUI(Unknown Source)
at javax.swing.JInternalFrame$JDesktopIcon.<init>(Unknown Source)
at javax.swing.JInternalFrame.<init>(Unknown Source)
at RalphVince.Controls.JScrollableDesktopPane.BaseInternalFrame.<init>()
- 6
- JavaScript for MaximizationHi. I want onLoad(), to make my current IE window "maximized." I can resize
the window to Screen.width/height but the problem with that is that it
includes the full screen height (including the task-bar) and I need it to be
without the task bar. Any way to do this? Preferably a way that's
browser-independant but IE-specific if need be.
Alex
- 7
- Creating Object With Methods During RuntimeHello All,
Is there a way to have a method create and name an object?
If my question is not clear, what I mean is instead of this:
...
Person abc = new Person();
...
where the programmer specifies the name of the object and where in the
program it is created, you have a method something like this:
...
//the string that is passed to this method is generated by another
//function which generates random strings - in other words, neither
//the programmer nor the user are involved in this step directly
private void createObject(String s)
{
Person s = new Person();
}
...
This might be used in a GUI simulation that is modeling the interaction
of different species in an ecosystem, for example. At some point the
user may wish to increase the complexity of the sim by adding more
creatures of one type or another. They could press a button which would
call the createObject function and insert another animal into the fray.
I hope that is enough to sufficiently explain what I am asking, in any case.
By the way, just in case you are wondering, I have not tested the
example function above (I know it won't work as is). Normally I would
try myself before asking here, but I don't have access to my PC right
now and I can't find what I'm looking for on the internet.
Thanks very much to any who can help.
A
- 8
- Long delay using SSLSocketFactoryHi all,
I need to do HTTPS requests from a WLS container through a proxy which
requires encoded username/password authentication. Therefore, I am
using an extension of SSLSocketFactory (part of SUN's JSSE), which
does the proxy authentication for me and the tunnel handshake as well.
Principally, the solution I thought of works. However, after starting
the WLS, the very first connection to the proxy takes more than two
minutes. Running the test once again, the connection to the proxy is
established almost instantaneously. Can anyone explain the long delay
in the first connection? It occurs when invoking method
SSLSocketFactory.getDefault() (see the below code snippet).
I scanned the port of the proxy and found no activity during the
delay. Neither, there are any outgoing TCP packages from the source
machine (where the JVM is running). So I assume that the delay is not
due to a network problem; it must be somewhere in the depths of the
JSSE classes.
Best regards,
Thomas Mantay
Here is the code I am using:
import java.net.*;
import java.io.*;
import java.security.*;
import sun.misc.BASE64Encoder;
import javax.net.*;
import javax.net.ssl.*;
public class SSLTunnelSocketFactory extends SSLSocketFactory {
private String tunnelHost;
private int tunnelPort;
private SSLSocketFactory dfactory;
private String tunnelPassword;
private String tunnelUserName;
private boolean socketConnected = false;
private int falsecount = 0;
/**
* Constructor for the SSLTunnelSocketFactory object
*
*@param proxyHost The url of the proxy host
*@param proxyPort the port of the proxy
*@param proxyUserName username for authenticating with the
proxy
*@param proxyPassword password for authenticating with the
proxy
*/
public SSLTunnelSocketFactory(String proxyHost, int proxyPort,
String proxyUserName, String proxyPassword) {
NLUtil.ldebug("SSLTunnelSocketFactory", "Constructor", "creating
Socket Factory with password/username");
tunnelHost = proxyHost;
tunnelPort = proxyPort;
tunnelUserName = proxyUserName;
tunnelPassword = proxyPassword;
NLUtil.ldebug("SSLTunnelSocketFactory", "Constructor", "before
getDefault()");
Here is the line that causes the delay:
dfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
NLUtil.ldebug("SSLTunnelSocketFactory", "Constructor", "after
getDefault()");
}
/**
* Gets the supportedCipherSuites attribute of the
SSLTunnelSocketFactory
* object
*
*@return The supportedCipherSuites value
*/
public String[] getSupportedCipherSuites() {
return dfactory.getSupportedCipherSuites();
}
/**
* Gets the defaultCipherSuites attribute of the
SSLTunnelSocketFactory
* object
*
*@return The defaultCipherSuites value
*/
public String[] getDefaultCipherSuites() {
return dfactory.getDefaultCipherSuites();
}
/**
* Gets the socketConnected attribute of the
SSLTunnelSocketFactory object
*
*@return The socketConnected value
*/
public synchronized boolean getSocketConnected() {
return socketConnected;
}
/**
* Creates a new SSL Tunneled Socket
*
*@param s Ignored
*@param host destination host
*@param port destination port
*@param autoClose wether to close the socket
automaticly
*@return proxy tunneled socket
*@exception IOException raised by an IO error
*@exception UnknownHostException raised when the host is
unknown
*/
public Socket createSocket(Socket s, String host, int port,
boolean autoClose)
throws IOException, UnknownHostException {
Socket tunnel = new Socket(tunnelHost, tunnelPort);
doTunnelHandshake(tunnel, host, port);
SSLSocket result = (SSLSocket) dfactory.createSocket(tunnel,
host, port, autoClose);
result.addHandshakeCompletedListener(
new HandshakeCompletedListener() {
public void handshakeCompleted(HandshakeCompletedEvent
event) {
NLUtil.ldebug("SSLTunnelSocketFactory", "handshakeCompleted",
"Handshake Finished!");
NLUtil.ldebug("SSLTunnelSocketFactory", "handshakeCompleted",
"CipherSuite :" + event.getCipherSuite());
NLUtil.ldebug("SSLTunnelSocketFactory", "handshakeCompleted",
"SessionId: " + event.getSession());
NLUtil.ldebug("SSLTunnelSocketFactory", "handshakeCompleted",
"PeerHost: " + event.getSession().getPeerHost());
setSocketConnected(true);
}
});
// thanks to David Lord in the java forums for figuring out
this line is the problem
// result.startHandshake(); //this line is the bug which stops
Tip111 from working correctly
return result;
}
/**
* Creates a new SSL Tunneled Socket
*
*@param host destination host
*@param port destination port
*@return tunneled SSL Socket
*@exception IOException raised by IO error
*@exception UnknownHostException raised when the host is
unknown
*/
public Socket createSocket(String host, int port)
throws IOException, UnknownHostException {
return createSocket(null, host, port, true);
}
/**
* Creates a new SSL Tunneled Socket
*
*@param host Destination Host
*@param port Destination Port
*@param clientHost Ignored
*@param clientPort Ignored
*@return SSL Tunneled Socket
*@exception IOException Raised when IO error occurs
*@exception UnknownHostException Raised when the destination
host is
* unknown
*/
public Socket createSocket(String host, int port, InetAddress
clientHost,
int clientPort)
throws IOException, UnknownHostException {
return createSocket(null, host, port, true);
}
/**
* Creates a new SSL Tunneled Socket
*
*@param host destination host
*@param port destination port
*@return tunneled SSL Socket
*@exception IOException raised when IO error occurs
*/
public Socket createSocket(InetAddress host, int port)
throws IOException {
return createSocket(null, host.getHostName(), port, true);
}
/**
* Creates a new SSL Tunneled Socket
*
*@param address destination host
*@param port destination port
*@param clientAddress ignored
*@param clientPort ignored
*@return tunneled SSL Socket
*@exception IOException raised when IO exception occurs
*/
public Socket createSocket(InetAddress address, int port,
InetAddress clientAddress, int clientPort)
throws IOException {
return createSocket(null, address.getHostName(), port, true);
}
/**
* Sets the socketConnected attribute of the
SSLTunnelSocketFactory object
*
*@param b The new socketConnected value
*/
private synchronized void setSocketConnected(boolean b) {
socketConnected = b;
}
/**
* Description of the Method
*
*@param tunnel tunnel socket
*@param host destination host
*@param port destination port
*@exception IOException raised when an IO error occurs
*/
private void doTunnelHandshake(Socket tunnel, String host, int
port) throws IOException {
NLUtil.ldebug("SSLTunnelSocketFactory", "doTunnelHandshake",
"doTunnelHandshake start");
OutputStream out = tunnel.getOutputStream();
//generate connection string
String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n"
+ "User-Agent: "
+ sun.net.www.protocol.http.HttpURLConnection.userAgent;
if (!tunnelUserName.equals("") && !tunnelPassword.equals(""))
{
NLUtil.ldebug("SSLTunnelSocketFactory", "doTunnelHandshake",
"Using proxy authencation with username '" + tunnelUserName + "' and
password '" + tunnelPassword + "'.");
//add basic authentication header for the proxy
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
String encodedPassword = enc.encode((tunnelUserName + ":"
+ tunnelPassword).getBytes());
msg = msg + "\nProxy-Authorization: Basic " +
encodedPassword;
}
msg = msg + "\nContent-Length: 0";
msg = msg + "\nPragma: no-cache";
msg = msg + "\r\n\r\n";
NLUtil.ldebug("SSLTunnelSocketFactory", "doTunnelHandshake", "msg:
" + msg);
byte b[];
try {
//we really do want ASCII7 as the http protocol doesnt
change with locale
b = msg.getBytes("ASCII7");
} catch (UnsupportedEncodingException ignored) {
//If ASCII7 isn't there, something is seriously wrong!
b = msg.getBytes();
}
out.write(b);
out.flush();
byte reply[] = new byte[200];
int replyLen = 0;
int newlinesSeen = 0;
boolean headerDone = false;
InputStream in = tunnel.getInputStream();
boolean error = false;
while (newlinesSeen < 2) {
int i = in.read();
if (i < 0) {
throw new IOException("Unexpected EOF from Proxy");
}
if (i == '\n') {
headerDone = true;
++newlinesSeen;
} else
if (i != '\r') {
newlinesSeen = 0;
if (!headerDone && replyLen < reply.length) {
reply[replyLen++] = (byte) i;
}
}
}
//convert byte array to string
String replyStr;
try {
replyStr = new String(reply, 0, replyLen, "ASCII7");
} catch (UnsupportedEncodingException ignored) {
replyStr = new String(reply, 0, replyLen);
}
//we check for connection established because our proxy
returns http/1.1 instead of 1.0
if (replyStr.toLowerCase().indexOf("200 connection
established") == -1) {
NLUtil.ldebug("SSLTunnelSocketFactory", "doTunnelHandshake",
"replyStr: " + replyStr);
System.err.println(replyStr);
throw new IOException("Unable to tunnel through " +
tunnelHost + ":" + tunnelPort + ". Proxy returns\"" + replyStr +
"\"");
}
//tunneling hanshake was successful
}
}
- 9
- Final member troubleimport java.awt.Image;
import javax.imageio.ImageIO;
import java.io.*;
public class FinalTryCatch {
final Image someImage;
public FinalTryCatch() {
try {
someImage = ImageIO.read(new File("someImageFile.gif"));
} catch (IOException ioe) {
someImage = null;
}
}
public static void main(String[] args) {
FinalTryCatch f = new FinalTryCatch();
// Do some stuff
}
}
This fails to compile with "variable someImage might already have been
assigned" on "someImage = null;". Remove that line and it complains,
"variable someImage might not have been initialized". Obviously. What would
you do in this situation? Make the variable non-final? Have the constructor
throw IOException? Something else?
- 10
- why allow multiple classes in one file?Hello,
I'm pretty new to Java, so please don't yell at me if my question is
dumb.
Each public file should be in a separate file. I don't understand why
is it allowed for a file contain additional non-public (default)
classes. Why is it not one class per file, public or default?
Thanks,
Hilbert
- 11
- converting paper space to model space in dxf filesHello wise guys!
I'm writing a piece of code (java) that shold parse and draw the
content of a DXF file. The trouble is that some blocks (usually texts
or legend) are given in paper space. Can anyone give me a hint how
paper coordinates should be converted to model coordinates? Thanks a
lot!
Adrian
- 12
- 13
- JTextField : limit number of input charactersHi,
How can I do limit the number of character into a JTextField component ? I'm
a Newbie, and I've some problem with this.
Other question, in a JTable, how can I do to put a DropDown into a field
from a column ?
Thanks for all
Bernard
- 14
- aliasHi,
I may be jumping guns here. I mean I'm totally new to java and yet, I
feel the need to do something like this for typing much less,
o = System.out.println; // problem, what data type for var of o here?
undefined.
or
alias o = System.out.println; // alias is supposed to be a special
command or the sort?
then, I do something like this
for (int i=0; i < 5; i++) {
switch(i)
case 0:
case 2:
case 4:
o(i + " is an even number"); // instead of System.out.println(i +
" is an even number");
break;
case 1:
case 3:
case 5:
o(i + " is an odd number"); // instead of System.out.println(i + "
is an odd number");
break;
default:
o(i + " is neither an odd nor even number");
// instead of System.out.println(i + " is neither an odd nor even
number");
}
Doable? How? TIA.
- 15
- analytical Skill for Java Development> As an experiment, give an "experienced" developer a problem and watch
> their
> analytical and problem solving skills seriously fail him/her. This of
> course, is the general case - there may be some corner cases where this
> will
> not occur.
So how can one learn better problem solving skills? In addition to
problem solving, where can one find better algorithms to use?
|
|
|