GetLocalHost throws UnknownHostException
We have a situation where #getLocalHost will intermittently throw an UnknownHostException. I've checked etc/hosts and everything is normal, additionally, the machine is not using DNS.
The exception is a little odd in that the local host name is listed twice:
Caused by: java.net.UnknownHostException: myhost: myhost
at java.net.InetAddress.getLocalHost(InetAddress.java:1191)If I look at the source, it seems that the actual exception is being thrown from #getAddressFromNameService on this line:
byte_array = nameService.lookupAllHostAddr(host);Anyone run into this? What's odd is that it is intermittent, not predictable.
R.
Everyone gets annoyed at this one (especially when developing on a laptop). Here's a snippet of code I often use when testing code locally
* Best attempt to get the local hostname, with or without the existence of a DNS entry.
* @author [email protected]
* @return Short version of the local hostname.
* @throws UnknownHostException There is a problem with the DNS entry for this host and/or this JVM implementation
* does not return the standard error string.
public static String getLocalHostName() throws UnknownHostException {
try {
return (InetAddress.getLocalHost()).getHostName();
} catch ( UnknownHostException uhe ) {
String host = uhe.getMessage(); // host = "hostname: hostname"
if ( host!=null ) {
int colon = host.indexOf(':');
if ( colon>0 ) {
return host.substring(0, colon); // Dangerous, this is JVM dependant code.
throw uhe;
}
Similar Messages
-
When i am executing this statement from a simple java program its working fine. But when I call the statement from JSP or servlet, its throwing UnknownhostException.
I am using tomcat3.3.1 as web server running on Sun Solaris.
Is there problem with setting of tomcat ???
Please help me out.I tried nslookup at the shell prompt. It was showing unknown host for the ip address. I contacted our network people and came to know that the server is on internet and thats why it was not showing the local ip address host name in nslookup. Then I tried the internet ip address and host name of the server in the stetement and it worked out. Hope i am clear to u. Now the statement is running fine.
Actually I was trying to send mail using Smtp class and while dong that it was throwing UnknownHostException. Then i found out the Intaddress.getLocalHost() was the stmt throwing this error. Now as I am giving the internet address for constructor of new SmtpClient() method, it is not giving this error and my mail is getting delivered. But it processis taking lot of time. It takes @ 15 minutes to send a mail.
Can u help me out in this????
Thanx for help....... -
GetLocalhost() always throws UnknownHostException
Hi,
On my computer the method InetAddress.getLocalHost() always throws an UnknownHostException (JRE: jre-1_5_0_05-windows-i586-p.exe).
I found a topic for this trouble (http://forum.java.sun.com/thread.jspa?forumID=11&threadID=495321) but it doesn't help me.
I think there is a problem in my network configuration. Can you help me?
My OS is XP service pack 2.
>>>> Result of the command "ipconfig /all" (sorry it's in french, and I changed some number with "XXXX' for confidentiality)
Configuration IP de Windows
Nom de l'h�te . . . . . . . . . . : myhost
Suffixe DNS principal . . . . . . :
Type de noud . . . . . . . . . . : Inconnu
Routage IP activ� . . . . . . . . : Non
Proxy WINS activ� . . . . . . . . : Non
Carte Ethernet Connexion au r�seau local:
Suffixe DNS propre � la connexion :
Description . . . . . . . . . . . : 3Com Gigabit LOM (3C940)
Adresse physique . . . . . . . . .: 00-0C-6E-XX-XX-XX
DHCP activ�. . . . . . . . . . . : Oui
Configuration automatique activ�e . . . . : Oui
Adresse IP. . . . . . . . . . . . : 192.168.0.2
Masque de sous-r�seau . . . . . . : 255.255.255.0
Adresse IP. . . . . . . . . . . . : XXXX::XXXX:XXXX:fe85:ebb4%4
Passerelle par d�faut . . . . . . : 192.168.0.1
Serveur DHCP. . . . . . . . . . . : 192.168.0.1
Serveurs DNS . . . . . . . . . . : 192.168.0.1
fec0:0:0:ffff::1%1
fec0:0:0:ffff::2%1
fec0:0:0:ffff::3%1
Bail obtenu . . . . . . . . . . . : mardi 18 octobre 2005 18:16:51
Bail expirant . . . . . . . . . . : vendredi 21 octobre 2005
18:16:51
Carte Tunnel Teredo Tunneling Pseudo-Interface :
Suffixe DNS propre � la connexion :
Description . . . . . . . . . . . : Teredo Tunneling
Pseudo-Interface
Adresse physique . . . . . . . . .: FF-FF-FF-FF-FF-FF-FF-FF
DHCP activ�. . . . . . . . . . . : Non
Adresse IP. . . . . . . . . . . . : XXXX::5445:5245:444f%5
Passerelle par d�faut . . . . . . :
NetBIOS sur TCPIP. . . . . . . . : D�sactiv�
Carte Tunnel Automatic Tunneling Pseudo-Interface :
Suffixe DNS propre � la connexion :
Description . . . . . . . . . . . : Automatic Tunneling
Pseudo-Interface
Adresse physique . . . . . . . . .: C0-A8-00-02
DHCP activ�. . . . . . . . . . . : Non
Adresse IP. . . . . . . . . . . . : fe80::5efe:192.168.0.2%2
Passerelle par d�faut . . . . . . :
Serveurs DNS . . . . . . . . . . : fec0:0:0:ffff::1%1
fec0:0:0:ffff::2%1
fec0:0:0:ffff::3%1
NetBIOS sur TCPIP. . . . . . . . : D�sactiv�
Result of the "ping localhost" command:
ping localhost
Envoi d'une requ�te 'ping' sur myhost [::1] avec 32 octets de donn�es :
R�ponse de ::1 : temps<1ms
R�ponse de ::1 : temps<1ms
R�ponse de ::1 : temps<1ms
R�ponse de ::1 : temps<1ms
>>>> Result of the "route print" command
===========================================================================
Liste d'Interfaces
0x1 ........................... MS TCP Loopback interface
0x2 ...00 0c 6e XX XX XX ...... 3Com Gigabit LOM (3C940) - Miniport
d'ordonnance
ment de paquets ===========================================================================
===========================================================================
Itin�raires actifs :
Destination r�seau Masque r�seau Adr. passerelle Adr. interface
M�trique
0.0.0.0 0.0.0.0 192.168.0.1 192.168.0.2 20
64.4.XXX.XXX 255.255.255.255 192.168.0.1 192.168.0.2 20
65.54.XXX.XXX 255.255.255.255 192.168.0.1 192.168.0.2 20
127.0.0.0 255.0.0.0 127.0.0.1 127.0.0.1 1
192.168.0.0 255.255.255.0 192.168.0.2 192.168.0.2 20
192.168.0.2 255.255.255.255 127.0.0.1 127.0.0.1 20
192.168.0.255 255.255.255.255 192.168.0.2 192.168.0.2 20
207.46.XXX.XXX 255.255.255.255 192.168.0.1 192.168.0.2 20
207.68.XXX.XXX 255.255.255.255 192.168.0.1 192.168.0.2 20
224.0.0.0 240.0.0.0 192.168.0.2 192.168.0.2 20
255.255.255.255 255.255.255.255 192.168.0.2 192.168.0.2 1
Passerelle par d�faut : 192.168.0.1
===========================================================================
Itin�raires persistants :
AucunThank you!Just a guess, but try setting "Suffixe DNS propre � la connexion"
On my machine, I bring up the window Local Area Connection Status, then click on Properties, that brings up the Local Area Connection Properties window. Then I click on Internet Protocol (TCP/IP) in the list, then click the Properties button. That brings up the Internet Protocol (TCP/IP) Properties window; in there click Advanced button. That brings up the Advanced TCP/IP Settings window. In it click on the DNS tab. Down near the bottom is a box labeled "DNS suffix for this connection" and in it I have the suffix for my domain (berkeley.edu). I've never understood what the two boxes below are for/what they do.
This is just a stab in the dark; I have no idea if it will help. -
UnknownHostException:http
Hi all,
We are migrating an application from 5.1 to 7.0 version and when we access the url which belongs to the application it throws UnknownHostException:http .This is thrown in the class
public class DAVURLConnection extends sun.net.www.protocol.http.HttpURLConnection
And the stack trace is:
10/4/12 1:15:01:244 CDT 00000027 SystemErr R java.net.UnknownHostException: http
10/4/12 1:15:01:244 CDT 00000027 SystemErr R at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:207)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at java.net.Socket.connect(Socket.java:539)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at java.net.Socket.connect(Socket.java:488)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at sun.net.www.http.HttpClient.openServer(HttpClient.java:407)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at sun.net.www.http.HttpClient$4.run(HttpClient.java:470)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at java.security.AccessController.doPrivileged(AccessController.java:251)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at sun.net.www.http.HttpClient.privilegedOpenServer(HttpClient.java:452)
10/4/12 1:15:01:245 CDT 00000027 SystemErr R at sun.net.www.http.HttpClient.openServer(HttpClient.java:533)
10/4/12 1:15:01:246 CDT 00000027 SystemErr R at sun.net.www.http.HttpClient.<init>(HttpClient.java:246)
10/4/12 1:15:01:246 CDT 00000027 SystemErr R at sun.net.www.http.HttpClient.New(HttpClient.java:319)
10/4/12 1:15:01:246 CDT 00000027 SystemErr R at sun.net.www.http.HttpClient.New(HttpClient.java:336)
10/4/12 1:15:01:246 CDT 00000027 SystemErr R at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:980)
10/4/12 1:15:01:246 CDT 00000027 SystemErr R at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:959)
10/4/12 1:15:01:246 CDT 00000027 SystemErr R at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
10/4/12 1:15:01:246 CDT 00000027 SystemErr R at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1024)
10/4/12 1:15:01:247 CDT 00000027 SystemErr R at com.ibm.webdav.protocol.http.DAVURLConnection.getOutputStream(DAVURLConnection.java:89)
To add more info . We did telnet for hostname to which we are trying to connect from the linux server for this we could able to telnet but when we try to connect that host through java code then we are getting the above specified stacktrace at getOutputStream() method. getOutputStream() method is overriden in above mentioned class WebDAVURLConnection and calling super.getOutputStream() method.Are we need to do any jar files inclusion after migrating to 7.0 version? Do we need to change code which uses this method ? Any suggestions.
Edited by: 962584 on Oct 4, 2012 4:57 AMThe code:
URL getUrl = new URL("ValidURL");
String protocol = getUrl.getProtocol();
int port = getUrl.getPort();
DAVURLConnection getUrlCon = new DAVURLConnection(getUrl, protocol, port);
getUrlCon.setDoInput(true);
getUrlCon.setRequestMethod("PUT");
getUrlCon.setRequestProperty("Content-type", "text/xml");
getUrlCon.setRequestProperty("Depth", depth);
getUrlCon.setFollowRedirects(false);
authenticate(cookieList, getUrlCon, respCode);
getUrlCon.setDoOutput(true);
OutputStream os = getUrlCon.getOutputStream(); --- getting exception at this point
============================================
In DAVURLConnection (Url , protocol, port) construtor, we are calling super(u, host, port) constructor of sun.net.www.protocol.http.HttpURLConnection.
i.e public DAVURLConnection(URL u, String host, int port) throws IOException {
super(u, host, port);
Edited by: 962584 on Oct 4, 2012 4:53 AM
Edited by: 962584 on Oct 4, 2012 4:56 AM -
Hi I am using a ftp class (known as FTPConnection) that i found on this site: http://www.nsftools.com/tips/JavaFtp.htm , and they only have an example of how to download a File through FTP and not upload one. I am in the proccess of making an FTP upload applet, and need some help on getting upload to work. I also need it to work on both a Pc and mac, so that may be attributing to the problem becuase i am currently on a mac which uses file:// instead of C:\\. Ill post the ftp class, and a snippet of my code that tries to upload a selected file.
FTPConnection
/* <!-- in case someone opens this in a browser... --> <pre> */
* File: FTPConnection.java
* Author: Bret Taylor <[email protected]>
* URL: http://www.stanford.edu/~bstaylor/cs/ftpconnection/FTPConnection.java.shtml
* see also <a href="http://www.nsftools.com/tips/JavaFtp.htm">http://www.nsftools.com/tips/JavaFtp.htm</a>
* $Id$
* Parts of this code were adopted from a variety of other FTP classes the
* author has encountered that he was not completely satisfied with. If you
* think more thanks are due to any particular author than is given, please
* let him know. With that caveat, this class can be freely distributed and
* modified as long as Bret Taylor is given credit in the source code comments.
* Modified by Julian Robichaux -- http://www.nsftools.com
* Added constructors, logout(), listFiles(), listSubdirectories(), getAndParseDirList(),
* processFileListCommand(), and overloaded getFullServerReply().
* Also added StringBuffer parameter options to transferData() and executeDataCommand()
* and did a few other little things.
import java.io.*;
import java.net.*;
import java.util.*;
* <p>A wrapper for the network and command protocols needed for the most common
* FTP commands. Standard usage looks something like this:</p>
* <pre> FTPConnection connection = new FTPConnection();
* try {
* if (connection.connect(host)) {
* if (connection.login(username, password)) {
* connection.downloadFile(serverFileName);
* connection.uploadFile(localFileName);
* connection.disconnect();
* } catch (UnknownHostException e) {
* // handle unknown host
* } catch (IOException e) {
* // handle I/O exception
* }</pre>
* <p>Most FTP commands are wrapped by easy-to-use methods, but in case clients
* need more flexibility, you can execute commands directly using the methods
* <a href="#executeCommand(java.lang.String)">executeCommand</a> and
* <a href="#executeDataCommand(java.lang.String,
* java.io.OutputStream)">executeDataCommand</a>,
* the latter of which is used for commands that require an open data port.</p>
* @author Bret Taylor
* @author Julian Robichaux
* @version 1.01
public class FTPConnection extends Object {
* If this flag is on, we print out debugging information to stdout during
* execution. Useful for debugging the FTP class and seeing the server's
* responses directly.
private static boolean PRINT_DEBUG_INFO = false;
* The socket through which we are connected to the FTP server.
private Socket connectionSocket = null;
private String username;
private String password;
private String host;
* The socket output stream.
private PrintStream outputStream = null;
* The socket input stream.
private BufferedReader inputStream = null;
* The offset at which we resume a file transfer.
private long restartPoint = 0L;
* Added by Julian: If this flag is on, we're currently logged in to something.
private boolean loggedIn = false;
* Added by Julian: This is the line terminator to use for multi-line responses.
public String lineTerm = "\n";
* Added by Julian: This is the size of the data blocks we use for transferring
* files.
private static int BLOCK_SIZE = 4096;
* Added by Julian: After you create an FTPConnection object, you will call the
* connect() and login() methods to access your server. Please don't forget to
* logout() and disconnect() when you're done (it's only polite...).
public FTPConnection ()
// default constructor (obviously) -- this is just good to have...
* Added by Julian: Allows you to specify if you want to send debug output to
* the console (true if you do, false if you don't).
public FTPConnection (boolean debugOut)
PRINT_DEBUG_INFO = debugOut;
public FTPConnection (String user, String pw, String host_)
username=user;
password=pw;
host=host_;
PRINT_DEBUG_INFO = false;
* Prints debugging information to stdout if the private flag
* <code>PRINT_DEBUG_INFO</code> is turned on.
private void debugPrint(String message) {
if (PRINT_DEBUG_INFO) System.err.println(message);
* Connects to the given FTP host on port f, the default FTP port.
public boolean connect(String host)
throws UnknownHostException, IOException
return connect(host, 21);
* Connects to the given FTP host on the given port.
public boolean connect(String host, int port)
throws UnknownHostException, IOException
connectionSocket = new Socket(host, port);
connectionSocket.setSoTimeout(10000);
outputStream = new PrintStream(connectionSocket.getOutputStream());
inputStream = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
if (!isPositiveCompleteResponse(getServerReply())){
disconnect();
return false;
return true;
* Disconnects from the host to which we are currently connected.
static boolean URLexists(String URLName)
try
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
// HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
catch (Exception e)
e.printStackTrace();
return false;
public String getSimpleFileName(File f)
String path=f.getPath();
String fileName=path.replace("\\", "/");
int slashPos = fileName.lastIndexOf("/");
fileName=fileName.substring(slashPos+1);
return fileName;
public String verifyFileName(String name)
int count=0;
//String url="http://chris-malcolm.com/images/"+URLEncoder.encode(name).replace("+", "%20");
while (URLexists("http://chris-malcolm.com/images/"+URLEncoder.encode(name).replace("+", "%20"))==true)
count++;
name=FileExt(name)[0]+"-"+count+"."+FileExt(name)[1];
return name;
public String[] FileExt(String fileName)
int dotPos = fileName.lastIndexOf(".");
fileName=fileName.replace("\\", "/");
int slashPos = fileName.lastIndexOf("/");
String extension, name;
if (slashPos==fileName.length()-1)
fileName=fileName.substring(0, fileName.length()-1);
slashPos=fileName.lastIndexOf("/");
extension="/";
name=fileName.substring(slashPos+1);
else if(dotPos==-1)
name=fileName.substring(slashPos+1);
extension="";
else
extension = fileName.substring(dotPos+1);
name=fileName.substring(slashPos+1, dotPos);
String[] output={name, extension};
return output;
String[] output={name, extension};
return output;
public void disconnect()
if (outputStream != null) {
try {
if (loggedIn) { logout(); };
outputStream.close();
inputStream.close();
connectionSocket.close();
} catch (IOException e) {}
outputStream = null;
inputStream = null;
connectionSocket = null;
* Wrapper for the commands <code>user [username]</code> and <code>pass
* [password]</code>.
public boolean login(String username, String password)
throws IOException
int response = executeCommand("user " + username);
if (!isPositiveIntermediateResponse(response)) return false;
response = executeCommand("pass " + password);
loggedIn = isPositiveCompleteResponse(response);
return loggedIn;
* Added by Julian: Logout before you disconnect (this is good form).
public boolean logout()
throws IOException
int response = executeCommand("quit");
loggedIn = !isPositiveCompleteResponse(response);
return !loggedIn;
* Wrapper for the command <code>cwd [directory]</code>.
public boolean changeDirectory(String directory)
throws IOException
int response = executeCommand("cwd " + directory);
return isPositiveCompleteResponse(response);
* Wrapper for the commands <code>rnfr [oldName]</code> and <code>rnto
* [newName]</code>.
public boolean renameFile(String oldName, String newName)
throws IOException
int response = executeCommand("rnfr " + oldName);
if (!isPositiveIntermediateResponse(response)) return false;
response = executeCommand("rnto " + newName);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>mkd [directory]</code>.
public boolean makeDirectory(String directory)
throws IOException
int response = executeCommand("mkd " + directory);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>rmd [directory]</code>.
public boolean removeDirectory(String directory)
throws IOException
int response = executeCommand("rmd " + directory);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>cdup</code>.
public boolean parentDirectory()
throws IOException
int response = executeCommand("cdup");
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>dele [fileName]</code>.
public boolean deleteFile(String fileName)
throws IOException
int response = executeCommand("dele " + fileName);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>pwd</code>.
public String getCurrentDirectory()
throws IOException
String response = getExecutionResponse("pwd");
StringTokenizer strtok = new StringTokenizer(response);
// Get rid of the first token, which is the return code
if (strtok.countTokens() < 2) return null;
strtok.nextToken();
String directoryName = strtok.nextToken();
// Most servers surround the directory name with quotation marks
int strlen = directoryName.length();
if (strlen == 0) return null;
if (directoryName.charAt(0) == '\"') {
directoryName = directoryName.substring(1);
strlen--;
if (directoryName.charAt(strlen - 1) == '\"')
return directoryName.substring(0, strlen - 1);
return directoryName;
* Wrapper for the command <code>syst</code>.
public String getSystemType()
throws IOException
return excludeCode(getExecutionResponse("syst"));
* Wrapper for the command <code>mdtm [fileName]</code>. If the file does
* not exist, we return -1;
public long getModificationTime(String fileName)
throws IOException
String response = excludeCode(getExecutionResponse("mdtm " + fileName));
try {
return Long.parseLong(response);
} catch (Exception e) {
return -1L;
* Wrapper for the command <code>size [fileName]</code>. If the file does
* not exist, we return -1;
public long getFileSize(String fileName)
throws IOException
String response = excludeCode(getExecutionResponse("size " + fileName));
try {
return Long.parseLong(response);
} catch (Exception e) {
return -1L;
* Wrapper for the command <code>retr [fileName]</code>.
public boolean downloadFile(String fileName)
throws IOException
return readDataToFile("retr " + fileName, fileName);
* Wrapper for the command <code>retr [serverPath]</code>. The local file
* path to which we will write is given by <code>localPath</code>.
public boolean downloadFile(String serverPath, String localPath)
throws IOException
return readDataToFile("retr " + serverPath, localPath);
* Wrapper for the command <code>stor [fileName]</code>.
public boolean uploadFile(String fileName)
throws IOException
return writeDataFromFile("stor " + fileName, fileName);
* Wrapper for the command <code>stor [localPath]</code>. The server file
* path to which we will write is given by <code>serverPath</code>.
public boolean uploadFile(String serverPath, String localPath)
throws IOException
return writeDataFromFile("stor " + serverPath, localPath);
* Set the restart point for the next download or upload operation. This
* lets clients resume interrupted uploads or downloads.
public void setRestartPoint(int point)
restartPoint = point;
debugPrint("Restart noted");
* Gets server reply code from the control port after an ftp command has
* been executed. It knows the last line of the response because it begins
* with a 3 digit number and a space, (a dash instead of a space would be a
* continuation).
private int getServerReply()
throws IOException
return Integer.parseInt(getFullServerReply().substring(0, 3));
* Gets server reply string from the control port after an ftp command has
* been executed. This consists only of the last line of the response,
* and only the part after the response code.
private String getFullServerReply()
throws IOException
String reply;
do {
reply = inputStream.readLine();
debugPrint(reply);
} while(!(Character.isDigit(reply.charAt(0)) &&
Character.isDigit(reply.charAt(1)) &&
Character.isDigit(reply.charAt(2)) &&
reply.charAt(3) == ' '));
return reply;
* Added by Julian: Returns the last line of the server reply, but also
* returns the full multi-line reply in a StringBuffer parameter.
private String getFullServerReply(StringBuffer fullReply)
throws IOException
String reply;
fullReply.setLength(0);
do {
reply = inputStream.readLine();
debugPrint(reply);
fullReply.append(reply + lineTerm);
} while(!(Character.isDigit(reply.charAt(0)) &&
Character.isDigit(reply.charAt(1)) &&
Character.isDigit(reply.charAt(2)) &&
reply.charAt(3) == ' '));
// remove any trailing line terminators from the fullReply
if (fullReply.length() > 0)
fullReply.setLength(fullReply.length() - lineTerm.length());
return reply;
* Added by Julian: Gets a list of files in the current directory.
public String listFiles()
throws IOException
return listFiles("");
* Added by Julian: Gets a list of files in either the current
* directory, or one specified as a parameter. The 'params' parameter
* can be either a directory name, a file mask, or both (such as
* '/DirName/*.txt').
public String listFiles(String params)
throws IOException
StringBuffer files = new StringBuffer();
StringBuffer dirs = new StringBuffer();
if (!getAndParseDirList(params, files, dirs))
debugPrint("Error getting file list");
return files.toString();
* Added by Julian: Gets a list of subdirectories in the current directory.
public String listSubdirectories()
throws IOException
return listSubdirectories("");
* Added by Julian: Gets a list of subdirectories in either the current
* directory, or one specified as a parameter. The 'params' parameter
* can be either a directory name, a name mask, or both (such as
* '/DirName/Sub*').
public String listSubdirectories(String params)
throws IOException
StringBuffer files = new StringBuffer();
StringBuffer dirs = new StringBuffer();
if (!getAndParseDirList(params, files, dirs))
debugPrint("Error getting dir list");
return dirs.toString();
* Added by Julian: Sends and gets the results of a file list command,
* like LIST or NLST.
private String processFileListCommand(String command)
throws IOException
StringBuffer reply = new StringBuffer();
String replyString;
// file listings require you to issue a PORT command,
// like a file transfer
boolean success = executeDataCommand(command, reply);
if (!success)
return "";
replyString = reply.toString();
// strip the trailing line terminator from the reply
if (reply.length() > 0)
return replyString.substring(0, reply.length() - 1);
} else {
return replyString;
* Added by Julian: Gets a directory list from the server and parses
* the elements into a list of files and a list of subdirectories.
private boolean getAndParseDirList(String params, StringBuffer files, StringBuffer dirs)
throws IOException
// reset the return variables (we're using StringBuffers instead of
// Strings because you can't change a String value and pass it back
// to the calling routine -- changing a String creates a new object)
files.setLength(0);
dirs.setLength(0);
// get the NLST and the LIST -- don't worry if the commands
// don't work, because we'll just end up sending nothing back
// if that's the case
String shortList = processFileListCommand("nlst " + params);
String longList = processFileListCommand("list " + params);
// tokenize the lists we got, using a newline as a separator
StringTokenizer sList = new StringTokenizer(shortList, "\n");
StringTokenizer lList = new StringTokenizer(longList, "\n");
// other variables we'll need
String sString;
String lString;
// assume that both lists have the same number of elements
while ((sList.hasMoreTokens()) && (lList.hasMoreTokens())) {
sString = sList.nextToken();
lString = lList.nextToken();
if (lString.length() > 0)
if (lString.startsWith("d"))
dirs.append(sString.trim() + lineTerm);
debugPrint("Dir: " + sString);
} else if (lString.startsWith("-")) {
files.append(sString.trim() + lineTerm);
debugPrint("File: " + sString);
} else {
// actually, symbolic links will start with an "l"
// (lowercase L), but we're not going to mess with
// those
debugPrint("Unknown: " + lString);
// strip off any trailing line terminators and return the values
if (files.length() > 0) { files.setLength(files.length() - lineTerm.length()); }
if (dirs.length() > 0) { dirs.setLength(dirs.length() - lineTerm.length()); }
return true;
* Executes the given FTP command on our current connection, returning the
* three digit response code from the server. This method only works for
* commands that do not require an additional data port.
public int executeCommand(String command)
throws IOException
outputStream.println(command);
return getServerReply();
* Executes the given FTP command on our current connection, returning the
* last line of the server's response. Useful for commands that return
* one line of information.
public String getExecutionResponse(String command)
throws IOException
outputStream.println(command);
return getFullServerReply();
* Executes the given ftpd command on the server and writes the results
* returned on the data port to the file with the given name, returning true
* if the server indicates that the operation was successful.
public boolean readDataToFile(String command, String fileName)
throws IOException
// Open the local file
RandomAccessFile outfile = new RandomAccessFile(fileName, "rw");
// Do restart if desired
if (restartPoint != 0) {
debugPrint("Seeking to " + restartPoint);
outfile.seek(restartPoint);
// Convert the RandomAccessFile to an OutputStream
FileOutputStream fileStream = new FileOutputStream(outfile.getFD());
boolean success = executeDataCommand(command, fileStream);
outfile.close();
return success;
* Executes the given ftpd command on the server and writes the contents
* of the given file to the server on an opened data port, returning true
* if the server indicates that the operation was successful.
public boolean writeDataFromFile(String command, String fileName)
throws IOException
// Open the local file
RandomAccessFile infile = new RandomAccessFile(fileName, "r");
// Do restart if desired
if (restartPoint != 0) {
debugPrint("Seeking to " + restartPoint);
infile.seek(restartPoint);
// Convert the RandomAccessFile to an InputStream
FileInputStream fileStream = new FileInputStream(infile.getFD());
boolean success = executeDataCommand(command, fileStream);
infile.close();
return success;
* Executes the given ftpd command on the server and writes the results
* returned on the data port to the given OutputStream, returning true
* if the server indicates that the operation was successful.
public boolean executeDataCommand(String command, OutputStream out)
throws IOException
// Open a data socket on this computer
ServerSocket serverSocket = new ServerSocket(0);
if (!setupDataPort(command, serverSocket)) return false;
Socket clientSocket = serverSocket.accept();
// Transfer the data
InputStream in = clientSocket.getInputStream();
transferData(in, out);
// Clean up the data structures
in.close();
clientSocket.close();
serverSocket.close();
return isPositiveCompleteResponse(getServerReply());
* Executes the given ftpd command on the server and writes the contents
* of the given InputStream to the server on an opened data port, returning
* true if the server indicates that the operation was successful.
public boolean executeDataCommand(String command, InputStream in)
throws IOException
// Open a data socket on this computer
ServerSocket serverSocket = new ServerSocket(0);
if (!setupDataPort(command, serverSocket)) return false;
Socket clientSocket = serverSocket.accept();
// Transfer the data
OutputStream out = clientSocket.getOutputStream();
transferData(in, out);
// Clean up the data structures
out.close();
clientSocket.close();
serverSocket.close();
return isPositiveCompleteResponse(getServerReply());
* Added by Julian: Executes the given ftpd command on the server
* and writes the results returned on the data port to the given
* StringBuffer, returning true if the server indicates that the
* operation was successful.
public boolean executeDataCommand(String command, StringBuffer sb)
throws IOException
// Open a data socket on this computer
ServerSocket serverSocket = new ServerSocket(0);
if (!setupDataPort(command, serverSocket)) return false;
Socket clientSocket = serverSocket.accept();
// Transfer the data
InputStream in = clientSocket.getInputStream();
transferData(in, sb);
// Clean up the data structures
in.close();
clientSocket.close();
serverSocket.close();
return isPositiveCompleteResponse(getServerReply());
* Transfers the data from the given input stream to the given output
* stream until we reach the end of the stream.
private void transferData(InputStream in, OutputStream out)
throws IOException
byte b[] = new byte[BLOCK_SIZE];
int amount;
// Read the data into the file
while ((amount = in.read(b)) > 0) {
out.write(b, 0, amount);
* Added by Julian: Transfers the data from the given input stream
* to the given StringBuffer until we reach the end of the stream.
private void transferData(InputStream in, StringBuffer sb)
throws IOException
byte b[] = new byte[BLOCK_SIZE];
int amount;
// Read the data into the StringBuffer
while ((amount = in.read(b)) > 0) {
sb.append(new String(b, 0, amount));
* Executes the given ftpd command on the server and writes the results
* returned on the data port to the given FilterOutputStream, returning true
* if the server indicates that the operation was successful.
private boolean setupDataPort(String command, ServerSocket serverSocket)
throws IOException
// Send our local data port to the server
if (!openPort(serverSocket)) return false;
// Set binary type transfer
outputStream.println("type i");
if (!isPositiveCompleteResponse(getServerReply())) {
debugPrint("Could not set transfer type");
return false;
// If we have a restart point, send that information
if (restartPoint != 0) {
outputStream.println("rest " + restartPoint);
restartPoint = 0;
// TODO: Interpret server response here
getServerReply();
// Send the command
outputStream.println(command);
return isPositivePreliminaryResponse(getServerReply());
* Get IP address and port number from serverSocket and send them via the
* <code>port</code> command to the ftp server, returning true if we get a
* valid response from the server, returning true if the server indicates
* that the operation was successful.
private boolean openPort(ServerSocket serverSocket)
throws IOException
int localport = serverSocket.getLocalPort();
// get local ip address
InetAddress inetaddress = serverSocket.getInetAddress();
InetAddress localip;
try {
localip = inetaddress.getLocalHost();
} catch(UnknownHostException e) {
debugPrint("Can't get local host");
return false;
// get ip address in high byte order
byte[] addrbytes = localip.getAddress();
// tell server what port we are listening on
short addrshorts[] = new short[4];
// problem: bytes greater than 127 are printed as negative numbers
for(int i = 0; i <= 3; i++) {
addrshorts[i] = addrbytes;
if (addrshorts[i] < 0)
addrshorts[i] += 256;
outputStream.println("port " + addrshorts[0] + "," + addrshorts[1] +
"," + addrshorts[2] + "," + addrshorts[3] + "," +
((localport & 0xff00) >> 8) + "," +
(localport & 0x00ff));
return isPositiveCompleteResponse(getServerReply());
* True if the given response code is in the 100-199 range.
private boolean isPositivePreliminaryResponse(int response)
return (response >= 100 && response < 200);
* True if the given response code is in the 300-399 range.
private boolean isPositiveIntermediateResponse(int response)
return (response >= 300 && response < 400);
* True if the given response code is in the 200-299 range.
private boolean isPositiveCompleteResponse(int response)
return (response >= 200 && response < 300);
* True if the given response code is in the 400-499 range.
private boolean isTransientNegativeResponse(int response)
return (response >= 400 && response < 500);
* True if the given response code is in the 500-5ok i tried explaining th eproblem in the previous post, but i apologize if my explanation was poor. anyways, i tried to look into it further by doing a printStackTrace() and believe it may be a read error. here is my new updated snippet, and also a link to a screenshot ([click here for screenshot|http://img143.imageshack.us/my.php?image=picture4qr0.png]) of what the error looks like on my end. it seems like a socket is not being read, or maybe it is initialized properly. Again I apologize if my problem is vague, but I do appreciate your input. thanks.
updated code snippet
public void uploadFiles()
statusLabel.setVisible(true);
errorLabel.setVisible(true);
uploadButton.setVisible(false);
footer.setVisible(false);
holdingPanel.setVisible(false);
pbar.setVisible(true);
pbar = new JProgressBar();
pbar.setMinimum(0);
float Total=0;
for (int i=0; i<fileLengths.size(); i++)
if(((java.lang.Boolean)model.getValueAt(i,1)).toString().equals("true"))
Total+=Float.parseFloat((String)fileLengths.get(i));
pbar.setMaximum((int)Total);
String info="";
try
ftp=new FTPConnection(false);
ftp.connect("ftp.chris-malcolm.com");
if (ftp.login("chrismal", "***"))
statusLabel.setText("Status: Connected.");
info+="Successfully logged in!\n";
info+="System type is: " + ftp.getSystemType()+"\n";
info+="Current directory is: " + ftp.getCurrentDirectory()+"\n";
if (ftp.changeDirectory("/www/images/"))
info+="directory changed to: " + ftp.getCurrentDirectory()+"\n";
try
for (int i=0; i<allFiles.size(); i++)
if(((java.lang.Boolean)model.getValueAt(i,1)).toString().equals("true"))
String f=client.verifyFileName((String)model.getValueAt(i,0));
String f2=""+((File)allFiles.get(i)).getPath();
info+="filename: "+f2+"\n";
if (ftp.uploadFile(f2))
statusLabel.setText("Status: Uploading "+f+" - "+i+" of "+calculateTotalFiles()+" files(s)");
pbar.setValue(Integer.parseInt((String)fileLengths.get(i)));
else
errorLabel.setText("Error occured while uploading"+f2+"\n");
catch(Exception de)
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
de.printStackTrace(pw);
pw.close();
//errorLabel.setText("<html>ERROR:"+sw.toString().replace("\n", "<br>")+"</html>");
info+="Error: "+de.getMessage()+"\n";
info+="Trace: "+sw+"\n";
try { ftp.disconnect(); statusLabel.setText("Status: disconnected.");} catch(Exception e2) {};
else
info+="could not change directory\n";
else
info+="could not login";
catch (Exception e)
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.close();
info+="Error: "+e.getMessage()+"\n";
info+="Trace: "+sw+"\n";
try { ftp.disconnect(); statusLabel.setText("Status: disconnected.");} catch(Exception e2) {};
errorLabel.setText("ERROR:"+info);
JOptionPane.showMessageDialog(this, info, "test", JOptionPane.PLAIN_MESSAGE);
try { ftp.disconnect(); statusLabel.setText("Status: disconnected.");} catch(Exception e2) {};
Edited by: cjm771 on Jul 13, 2008 7:23 PM -
Hello,
Does anybody know a way to get the sysid (or the current environment) at runtime using XSLT mapping.
Some simple java code is also Okay
Cheers
Emile
Message was edited by: Emile Hermans1) Write some Java code to get the hostname
package com.company.xi;
public class MappingFunctions {
public String getServerHostname()
throws UnknownHostException {
InetAddress myAddress = InetAddress.getLocalHost();
return myAddress.getHostName();
2) Package it in a JAR and load it into the IR as an imported archive.
3) Call it from your XSLT
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:mapping="java:com.company.xi.MappingFunctions">
<HostName><xsl:value-of select="mapping:getHostName()"/></HostName>
Thanks,
Jesse -
How to get system Hostname in java
Hi,
I am a java developer trying to get the hostname of the system from java class. Meaning want the value when i run the $hostname command in linux and my server is Linux server.
I am searching in the System Properties for the hostname but i could not get it
I am running IBM Websphere 5.2 and JDK 1.4.2 in my linux server.
Thanks for input
-APTry
package testing;
import java.net.*;
public class Test
public static void main(String[] args) throws UnknownHostException
System.out.println(InetAddress.getLocalHost().getHostName());
} -
How to use custom truststore?
Hi, I've written a simple ssl client (basing on jakarta commons httpclient project) that connects to IIS with SSL and it works only i f I add ssl certificate from IIS to the jre cacerts (using keytool import). The cacerts are automatically readed somehow (don't know how)
I want to make the whole thing more elastic and be able to provide my client with a path to cacerts / truststore / keystore. Am I doing it OK? I Currently it works...
BUT the loops that print certificates and trustores to screen are empty - for example keystore .getCertificateChain(alias); always returns null....
But IIS cert is inside
C:\\Program Files\\Java\\jre1.5.0_09\\lib\\security\\cacertsbbb
PS. I would like to avoid setting System properties in my code like System.setTruststore etc.
PS. Should be without sockets. Just extension of what i got.
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import javax.net.SocketFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.log4j.Logger;
import junit.framework.TestCase;
public class SSLSocketClient extends TestCase {
private URL keystoreUrl = null;
private String mockKeystoreUrl = "C:\\Program Files\\Java\\jre1.5.0_09\\lib\\security\\cacertsbbb";
private String keystorePassword = "changeit";
private URL truststoreUrl = null;
private String mockTruststoreUrl = "C:\\Program Files\\Java\\jre1.5.0_09\\lib\\security\\cacertsbbb";
private String truststorePassword = null;
private SSLContext sslcontext = null;
public void testSSLSocket() {
try {
SSLSocketClient client = new SSLSocketClient();
// client.createSocket("10.63.29.50", 443);
HttpConnectionParams params = new HttpConnectionParams();
InetAddress ia = InetAddress.getLocalHost();
// params.setParameter(arg0, arg1)
//client.createSocket("10.63.29.50", 443, ia, 444, params);
client.connect("10.63.29.50", 443, "/ssl2/index.html", params);
} catch (ConnectTimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
private static Logger log = Logger.getLogger(SSLSocketClient.class);
* private static KeyStore createKeyStore(final URL url, final String
* password) throws KeyStoreException, NoSuchAlgorithmException,
* CertificateException, IOException { if (url == null) { throw new
* IllegalArgumentException("Keystore url may not be null"); }
* KeyStore keystore = KeyStore.getInstance("jks");
* keystore.load(url.openStream(), password != null ? password
* .toCharArray() : null); return keystore; }
private KeyStore mockCreateKeyStore(final String url, final String password)
throws KeyStoreException, NoSuchAlgorithmException,
CertificateException, IOException {
if (url == null) {
throw new IllegalArgumentException("Keystore url may not be null");
InputStream keystoreStream = new FileInputStream(url);
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(keystoreStream, password != null ? password.toCharArray()
: null);
return keystore;
private KeyManager[] createKeyManagers(final KeyStore keystore,
final String password) throws KeyStoreException,
NoSuchAlgorithmException, UnrecoverableKeyException {
if (keystore == null) {
throw new IllegalArgumentException("Keystore may not be null");
KeyManagerFactory kmfactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, password != null ? password.toCharArray()
: null);
return kmfactory.getKeyManagers();
private TrustManager[] createTrustManagers(final KeyStore keystore)
throws KeyStoreException, NoSuchAlgorithmException {
if (keystore == null) {
throw new IllegalArgumentException("Keystore may not be null");
TrustManagerFactory tmfactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmfactory.init(keystore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
for (int i = 0; i < trustmanagers.length; i++) {
if (trustmanagers[i] instanceof X509TrustManager) {
trustmanagers[i] = new AuthSSLX509TrustManager(
(X509TrustManager) trustmanagers);
return trustmanagers;
private SSLContext createSSLContext() {
try {
KeyManager[] keymanagers = null;
TrustManager[] trustmanagers = null;
if (this.mockKeystoreUrl != null) {
KeyStore keystore = mockCreateKeyStore(this.mockKeystoreUrl,
this.keystorePassword);
//if (log.isDebugEnabled()) {
Enumeration aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = (String) aliases.nextElement();
Certificate[] certs = keystore
.getCertificateChain(alias);
if (certs != null) {
log.info("Certificate chain '" + alias + "':");
for (int c = 0; c < certs.length; c++) {
if (certs[c] instanceof X509Certificate) {
X509Certificate cert = (X509Certificate) certs[c];
log.info(" Certificate " + (c + 1) + ":");
log.info(" Subject DN: "
+ cert.getSubjectDN());
log.info(" Signature Algorithm: "
+ cert.getSigAlgName());
log.info(" Valid from: "
+ cert.getNotBefore());
log.info(" Valid until: "
+ cert.getNotAfter());
log
.info(" Issuer: "
+ cert.getIssuerDN());
keymanagers = createKeyManagers(keystore, this.keystorePassword);
if (this.mockTruststoreUrl != null) {
KeyStore keystore = mockCreateKeyStore(this.mockKeystoreUrl,
this.truststorePassword);
//if (log.isDebugEnabled()) {
Enumeration aliases = keystore.aliases();
while (aliases.hasMoreElements()) {
String alias = (String) aliases.nextElement();
log.debug("Trusted certificate '" + alias + "':");
Certificate trustedcert = keystore
.getCertificate(alias);
if (trustedcert != null
&& trustedcert instanceof X509Certificate) {
X509Certificate cert = (X509Certificate) trustedcert;
log.info(" Subject DN: " + cert.getSubjectDN());
log.info(" Signature Algorithm: "
+ cert.getSigAlgName());
log.info(" Valid from: " + cert.getNotBefore());
log.info(" Valid until: " + cert.getNotAfter());
log.info(" Issuer: " + cert.getIssuerDN());
trustmanagers = createTrustManagers(keystore);
SSLContext sslcontext = SSLContext.getInstance("SSL");
// /sslcontext.
sslcontext.init(keymanagers, trustmanagers, null);
return sslcontext;
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage(), e);
throw new RuntimeException("Unsupported algorithm exception: "
+ e.getMessage());
// throw new AuthSSLInitializationError("Unsupported algorithm
// exception: " + e.getMessage());
} catch (KeyStoreException e) {
log.error(e.getMessage(), e);
throw new RuntimeException("Keystore exception: " + e.getMessage());
// throw new AuthSSLInitializationError("Keystore exception: " +
// e.getMessage());
} catch (GeneralSecurityException e) {
log.error(e.getMessage(), e);
throw new RuntimeException("Key management exception: "
+ e.getMessage());
// throw new AuthSSLInitializationError("Key management exception: "
// + e.getMessage());
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new RuntimeException(
"I/O error reading keystore/truststore file: "
+ e.getMessage());
// throw new AuthSSLInitializationError("I/O error reading
// keystore/truststore file: " + e.getMessage());
private SSLContext getSSLContext() {
if (this.sslcontext == null) {
this.sslcontext = createSSLContext();
return this.sslcontext;
* Attempts to get a new socket connection to the given host within the
* given time limit.
* <p>
* To circumvent the limitations of older JREs that do not support connect
* timeout a controller thread is executed. The controller thread attempts
* to create a new socket within the given limit of time. If socket
* constructor does not return until the timeout expires, the controller
* terminates and throws an {@link ConnectTimeoutException}
* </p>
* @param host
* the host name/IP
* @param port
* the port on the host
* @param clientHost
* the local host name/IP to bind the socket to
* @param clientPort
* the port on the local machine
* @param params
* {@link HttpConnectionParams Http connection parameters}
* @return Socket a new socket
* @throws IOException
* @throws IOException
* if an I/O error occurs while creating the socket
* @throws UnknownHostException
* if the IP address of the host cannot be determined
public void connect(final String host, final int sport, final String query,
final HttpConnectionParams params) throws IOException {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("Bartek: Hostname is not matched for cert.");
return true;
URL wlsUrl = null;
wlsUrl = new URL("https", host, Integer.valueOf(sport).intValue(),
query);
System.out
.println(" Trying a new HTTPS connection using WLS client classes - "
+ wlsUrl.toString());
HttpsURLConnection sconnection = (HttpsURLConnection) wlsUrl
.openConnection();
SocketFactory socketfactory = getSSLContext().getSocketFactory();
* HttpsURLConnection sconnection = new HttpsURLConnection( wlsUrl);
sconnection.setHostnameVerifier(hv);
//sconnection.setSSLSocketFactory((SSLSocketFactory) socketfactory);
sconnection.setSSLSocketFactory((SSLSocketFactory) socketfactory);
//sconnection.setHostnameVerifier(hv);
tryConnection(sconnection, System.out);
public static void tryConnection(HttpsURLConnection connection,
OutputStream stream) throws IOException {
connection.connect();
String responseStr = "\t\t" + connection.getResponseCode() + " -- "
+ connection.getResponseMessage() + "\n\t\t"
+ connection.getContent().getClass().getName() + "\n";
connection.disconnect();
System.out.print(responseStr);
Message was edited by:
herbatniczek1- By default, the jre will read the user's cacerts which runs the program.
2- You can specify another cacerts this way :
System.setProperty("javax.net.ssl.trustStore", my_trust);
For the case 1 and 2, you need to put the certificate in the cacerts.. Or,
3- You implement a custom TrustManager which, for example, accepts all certificates :
class X509TrustManagerTrustAll implements X509TrustManager {
public boolean checkClientTrusted(java.security.cert.X509Certificate[] chain){
return true;
public boolean isServerTrusted(java.security.cert.X509Certificate[] chain){
return true;
public boolean isClientTrusted(java.security.cert.X509Certificate[] chain){
return true;
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}
and you call it in the right place in the code you wrote (SSLContext,..)
Hope it helps and deserves a duke star ;) -
StringIndexOutofBounds Exception while doing FTP operation
Hello, I got this exception at run time when I am doing my FTP operations
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:455)
at FTPConnection.getFullServerReply(FTPConnection.java:312)
at FTPConnection.getServerReply(FTPConnection.java:296)
at FTPConnection.executeCommand(FTPConnection.java:329)
at FTPConnection.login(FTPConnection.java:107)
at JEditor$FTPUpload.checkTF(JEditor.java:2755)
at JEditor$FTPUpload.actionPerformed(JEditor.java:2783)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
67)
at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
ctButton.java:1820)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
.java:419)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
istener.java:258)
at java.awt.Component.processMouseEvent(Component.java:5021)
at java.awt.Component.processEvent(Component.java:4818)
at java.awt.Container.processEvent(Container.java:1380)
at java.awt.Component.dispatchEventImpl(Component.java:3526)
at java.awt.Container.dispatchEventImpl(Container.java:1437)
at java.awt.Component.dispatchEvent(Component.java:3367)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3214
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:2929)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:2859)
at java.awt.Container.dispatchEventImpl(Container.java:1423)
at java.awt.Window.dispatchEventImpl(Window.java:1566)
at java.awt.Component.dispatchEvent(Component.java:3367)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
read.java:190)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
ad.java:144)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
The file that I used for my FTP is
* File: FTPConnection.java
* Author: Bret Taylor <[email protected]>
* $Id$
* Parts of this code were adopted from a variety of other FTP classes the
* author has encountered that he was not completely satisfied with. If you
* think more thanks are due to any particular author than is given, please
* let him know. With that caveat, this class can be freely distributed and
* modified as long as Bret Taylor is given credit in the source code comments.
import java.io.*;
import java.net.*;
import java.util.*;
* <p>A wrapper for the network and command protocols needed for the most common
* FTP commands. Standard usage looks something like this:</p>
* <pre> FTPConnection connection = new FTPConnection();
* try {
* if (connection.connect(host)) {
* if (connection.login(username, password)) {
* connection.downloadFile(serverFileName);
* connection.uploadFile(localFileName);
* connection.disconnect();
* } catch (UnknownHostException e) {
* // handle unknown host
* } catch (IOException e) {
* // handle I/O exception
* }</pre>
* <p>Most FTP commands are wrapped by easy-to-use methods, but in case clients
* need more flexibility, you can execute commands directly using the methods
* executeCommand and
* executeDataCommand,
* the latter of which is used for commands that require an open data port.</p>
* @author Bret Taylor
* @version 1.0
public class FTPConnection extends Object {
* If this flag is on, we print out debugging information to stdout during
* execution. Useful for debugging the FTP class and seeing the server's
* responses directly.
private static boolean PRINT_DEBUG_INFO = false;
* Connects to the given FTP host on port 21, the default FTP port.
public boolean connect(String host)
throws UnknownHostException, IOException
return connect(host, 21);
* Connects to the given FTP host on the given port.
public boolean connect(String host, int port)
throws UnknownHostException, IOException
connectionSocket = new Socket(host, port);
outputStream = new PrintStream(connectionSocket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
if (!isPositiveCompleteResponse(getServerReply())){
disconnect();
return false;
return true;
* Disconnects from the host to which we are currently connected.
public void disconnect()
if (outputStream != null) {
try {
outputStream.close();
inputStream.close();
connectionSocket.close();
} catch (IOException e) {}
outputStream = null;
inputStream = null;
connectionSocket = null;
* Wrapper for the commands <code>user [username]</code> and <code>pass
* [password]</code>.
public boolean login(String username, String password)
throws IOException
int response = executeCommand("user " + username);
if (!isPositiveIntermediateResponse(response)) return false;
response = executeCommand("pass " + password);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>cwd [directory]</code>.
public boolean changeDirectory(String directory)
throws IOException
int response = executeCommand("cwd " + directory);
return isPositiveCompleteResponse(response);
* Wrapper for the commands <code>rnfr [oldName]</code> and <code>rnto
* [newName]</code>.
public boolean renameFile(String oldName, String newName)
throws IOException
int response = executeCommand("rnfr " + oldName);
if (!isPositiveIntermediateResponse(response)) return false;
response = executeCommand("rnto " + newName);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>mkd [directory]</code>.
public boolean makeDirectory(String directory)
throws IOException
int response = executeCommand("mkd " + directory);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>rmd [directory]</code>.
public boolean removeDirectory(String directory)
throws IOException
int response = executeCommand("rmd " + directory);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>cdup</code>.
public boolean parentDirectory()
throws IOException
int response = executeCommand("cdup");
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>dele [fileName]</code>.
public boolean deleteFile(String fileName)
throws IOException
int response = executeCommand("dele " + fileName);
return isPositiveCompleteResponse(response);
* Wrapper for the command <code>pwd</code>.
public String getCurrentDirectory()
throws IOException
String response = getExecutionResponse("pwd");
StringTokenizer strtok = new StringTokenizer(response);
// Get rid of the first token, which is the return code
if (strtok.countTokens() < 2) return null;
strtok.nextToken();
String directoryName = strtok.nextToken();
// Most servers surround the directory name with quotation marks
int strlen = directoryName.length();
if (strlen == 0) return null;
if (directoryName.charAt(0) == '\"') {
directoryName = directoryName.substring(1);
strlen--;
if (directoryName.charAt(strlen - 1) == '\"')
return directoryName.substring(0, strlen - 1);
return directoryName;
* Wrapper for the command <code>syst</code>.
public String getSystemType()
throws IOException
return excludeCode(getExecutionResponse("syst"));
* Wrapper for the command <code>mdtm [fileName]</code>. If the file does
* not exist, we return -1;
public long getModificationTime(String fileName)
throws IOException
String response = excludeCode(getExecutionResponse("mdtm " + fileName));
try {
return Long.parseLong(response);
} catch (Exception e) {
return -1L;
* Wrapper for the command <code>size [fileName]</code>. If the file does
* not exist, we return -1;
public long getFileSize(String fileName)
throws IOException
String response = excludeCode(getExecutionResponse("size " + fileName));
try {
return Long.parseLong(response);
} catch (Exception e) {
return -1L;
* Wrapper for the command <code>retr [fileName]</code>.
public boolean downloadFile(String fileName)
throws IOException
return readDataToFile("retr " + fileName, fileName);
* Wrapper for the command <code>retr [serverPath]</code>. The local file
* path to which we will write is given by <code>localPath</code>.
public boolean downloadFile(String serverPath, String localPath)
throws IOException
return readDataToFile("retr " + serverPath, localPath);
* Wrapper for the command <code>stor [fileName]</code>.
public boolean uploadFile(String fileName)
throws IOException
return writeDataFromFile("stor " + fileName, fileName);
* Wrapper for the command <code>stor [localPath]</code>. The server file
* path to which we will write is given by <code>serverPath</code>.
public boolean uploadFile(String serverPath, String localPath)
throws IOException
return writeDataFromFile("stor " + serverPath, localPath);
* Set the restart point for the next download or upload operation. This
* lets clients resume interrupted uploads or downloads.
public void setRestartPoint(int point)
restartPoint = point;
debugPrint("Restart noted");
* Gets server reply code from the control port after an ftp command has
* been executed. It knows the last line of the response because it begins
* with a 3 digit number and a space, (a dash instead of a space would be a
* continuation).
private int getServerReply()
throws IOException
return Integer.parseInt(getFullServerReply().substring(0, 3));
* Gets server reply string from the control port after an ftp command has
* been executed. This consists only of the last line of the response,
* and only the part after the response code.
private String getFullServerReply()
throws IOException
String reply;
do {
reply = inputStream.readLine();
debugPrint(reply);
} while(!(Character.isDigit(reply.charAt(0)) &&
Character.isDigit(reply.charAt(1)) &&
Character.isDigit(reply.charAt(2)) &&
reply.charAt(3) == ' '));
return reply;
* Executes the given FTP command on our current connection, returning the
* three digit response code from the server. This method only works for
* commands that do not require an additional data port.
public int executeCommand(String command)
throws IOException
outputStream.println(command);
return getServerReply();
* Executes the given FTP command on our current connection, returning the
* last line of the server's response. Useful for commands that return
* one line of information.
public String getExecutionResponse(String command)
throws IOException
outputStream.println(command);
return getFullServerReply();
* Executes the given ftpd command on the server and writes the results
* returned on the data port to the file with the given name, returning true
* if the server indicates that the operation was successful.
public boolean readDataToFile(String command, String fileName)
throws IOException
// Open the local file
RandomAccessFile outfile = new RandomAccessFile(fileName, "rw");
// Do restart if desired
if (restartPoint != 0) {
debugPrint("Seeking to " + restartPoint);
outfile.seek(restartPoint);
// Convert the RandomAccessFile to an OutputStream
FileOutputStream fileStream = new FileOutputStream(outfile.getFD());
boolean success = executeDataCommand(command, fileStream);
outfile.close();
return success;
* Executes the given ftpd command on the server and writes the contents
* of the given file to the server on an opened data port, returning true
* if the server indicates that the operation was successful.
public boolean writeDataFromFile(String command, String fileName)
throws IOException
// Open the local file
RandomAccessFile infile = new RandomAccessFile(fileName, "r");
// Do restart if desired
if (restartPoint != 0) {
debugPrint("Seeking to " + restartPoint);
infile.seek(restartPoint);
// Convert the RandomAccessFile to an InputStream
FileInputStream fileStream = new FileInputStream(infile.getFD());
boolean success = executeDataCommand(command, fileStream);
infile.close();
return success;
* Executes the given ftpd command on the server and writes the results
* returned on the data port to the given OutputStream, returning true
* if the server indicates that the operation was successful.
public boolean executeDataCommand(String command, OutputStream out)
throws IOException
// Open a data socket on this computer
ServerSocket serverSocket = new ServerSocket(0);
if (!setupDataPort(command, serverSocket)) return false;
Socket clientSocket = serverSocket.accept();
// Transfer the data
InputStream in = clientSocket.getInputStream();
transferData(in, out);
// Clean up the data structures
in.close();
clientSocket.close();
serverSocket.close();
return isPositiveCompleteResponse(getServerReply());
* Executes the given ftpd command on the server and writes the contents
* of the given InputStream to the server on an opened data port, returning
* true if the server indicates that the operation was successful.
public boolean executeDataCommand(String command, InputStream in)
throws IOException
// Open a data socket on this computer
ServerSocket serverSocket = new ServerSocket(0);
if (!setupDataPort(command, serverSocket)) return false;
Socket clientSocket = serverSocket.accept();
// Transfer the data
OutputStream out = clientSocket.getOutputStream();
transferData(in, out);
// Clean up the data structures
out.close();
clientSocket.close();
serverSocket.close();
return isPositiveCompleteResponse(getServerReply());
* Transfers the data from the given input stream to the given output
* stream until we reach the end of the stream.
private void transferData(InputStream in, OutputStream out)
throws IOException
byte b[] = new byte[1024]; // 1K blocks I guess
int amount;
// Read the data into the file
while ((amount = in.read(b)) > 0) {
out.write(b, 0, amount);
* Executes the given ftpd command on the server and writes the results
* returned on the data port to the given FilterOutputStream, returning true
* if the server indicates that the operation was successful.
private boolean setupDataPort(String command, ServerSocket serverSocket)
throws IOException
// Send our local data port to the server
if (!openPort(serverSocket)) return false;
// Set binary type transfer
outputStream.println("type i");
if (!isPositiveCompleteResponse(getServerReply())) {
debugPrint("Could not set transfer type");
return false;
// If we have a restart point, send that information
if (restartPoint != 0) {
outputStream.println("rest " + restartPoint);
restartPoint = 0;
// TODO: Interpret server response here
getServerReply();
// Send the command
outputStream.println(command);
return isPositivePreliminaryResponse(getServerReply());
* Get IP address and port number from serverSocket and send them via the
* <code>port</code> command to the ftp server, returning true if we get a
* valid response from the server, returning true if the server indicates
* that the operation was successful.
private boolean openPort(ServerSocket serverSocket)
throws IOException
int localport = serverSocket.getLocalPort();
// get local ip address
InetAddress inetaddress = serverSocket.getInetAddress();
InetAddress localip;
try {
localip = inetaddress.getLocalHost();
} catch(UnknownHostException e) {
debugPrint("Can't get local host");
return false;
// get ip address in high byte order
byte[] addrbytes = localip.getAddress();
// tell server what port we are listening on
short addrshorts[] = new short[4];
// problem: bytes greater than 127 are printed as negative numbers
for(int i = 0; i <= 3; i++) {
addrshorts[i] = addrbytes;
if (addrshorts[i] < 0)
addrshorts[i] += 256;
outputStream.println("port " + addrshorts[0] + "," + addrshorts[1] +
"," + addrshorts[2] + "," + addrshorts[3] + "," +
((localport & 0xff00) >> 8) + "," +
(localport & 0x00ff));
return isPositiveCompleteResponse(getServerReply());
* True if the given response code is in the 100-199 range.
private boolean isPositivePreliminaryResponse(int response)
return (response >= 100 && response < 200);
* True if the given response code is in the 300-399 range.
private boolean isPositiveIntermediateResponse(int response)
return (response >= 300 && response < 400);
* True if the given response code is in the 200-299 range.
private boolean isPositiveCompleteResponse(int response)
return (response >= 200 && response < 300);
* True if the given response code is in the 400-499 range.
private boolean isTransientNegativeResponse(int response)
return (response >= 400 && response < 500);
* True if the given response code is in the 500-599 range.
private boolean isPermanentNegativeResponse(int response)
return (response >= 500 && response < 600);
* Eliminates the response code at the beginning of the response string.
private String excludeCode(String response)
if (response.length() < 5) return response;
return response.substring(4);
* Prints debugging information to stdout if the private flag
* <code>PRINT_DEBUG_INFO</code> is turned on.
private void debugPrint(String message) {
if (PRINT_DEBUG_INFO) System.err.println(message);
* The socket through which we are connected to the FTP server.
private Socket connectionSocket = null;
* The socket output stream.
private PrintStream outputStream = null;
* The socket input stream.
private BufferedReader inputStream = null;
* The offset at which we resume a file transfer.
private long restartPoint = 0L;
Please help me where am I wrong?
ThanksI would guess the error happens at this line:
} while(!(Character.isDigit(reply.charAt(0)) && ...
because apparently reply.length() is 0 at the point of failure, so charAt(0) is beyond the end of the string. You need to check the length first. -
Input-/ouputStream hanging
Hi all.
I'm having some trouble with sending an XML-file via outputstream.
I think the problem is, that the receiving part, a SAXBuilder, doesn't recognize any end of file in the incoming data, and therefore keeps reading. My assumption is based on the fact, that if the sender's outputstream is closed, the receiver reads everything just fine. Flushing the stream doesn't appear to have any effect.
How do I avoid this? Is it perhaps possible to communicate an EOF after sending the document?
ServerConnection (sender):
import java.io.*;
import java.net.*;
import java.net.InetAddress;
import java.util.ArrayList;
import fsr.universal_classes.Customer;
import java.math.BigDecimal;
import org.jdom.*;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
public class ServerConnection implements Runnable{
private InetAddress hostname;
private int portNumber;
private Socket connection;
private BufferedWriter out;
private BufferedReader in;
private boolean connected = false;
private String threadName = "ServerConnection";
public ServerConnection(){
new Thread(this).start();
@Override
public void run(){
connectToDatabase();
private synchronized void connectToDatabase(){
portNumber = 49352;
try {
hostname = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
threadMessage("Couldnt find local host");
try {
connection = new Socket(hostname, portNumber);
connected = true;
out = new BufferedWriter(new PrintWriter(connection.getOutputStream(),true));
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
catch (IOException e) {
System.out.println(e);
connected = false;
public ArrayList<Customer> getCustomers(){
// Create XML
Element root = new Element("request");
Element subject = new Element("subject");
subject.setText("getAllCustomers");
root.addContent(subject);
// Create document and set DocType
Document doc = new Document();
doc.setRootElement(root);
DocType xmlDoctype = new DocType("request", "src/commands.dtd");
doc.setDocType(xmlDoctype);
// Send XML
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getRawFormat());
try {
outputter.output(doc, out);
out.flush();
} catch (Exception e) {
System.err.println("Exception: " + e);
ArrayList<Customer> customersList = new ArrayList();
return customersList;
public void threadMessage(String message){
System.out.println(threadName + ": " + message);
Session (Receiver):
import java.net.*;
import java.io.*;
import fsr.server.exceptions.SessionStoppedException;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
public class Session implements Runnable{
private Socket socket;
private int id;
private TCPServer tcpServer;
private boolean connected = true;
private SAXBuilder documentBuilder;
private String threadName = "Session";
public Session(Socket socket, int id) {
this.tcpServer = TCPServer.getInstance();
this.socket = socket;
this.id = id;
new Thread(this).start();
@Override
public void run() {
try {
communicate();
catch(SessionStoppedException e){
threadMessage("Session stopped: " + e.getError());
catch(Throwable t){
threadMessage("Session stopped (2)");
public void communicate() throws SessionStoppedException {
InputStreamReader ins;
try {
threadMessage("Getting input Stream");
ins = new InputStreamReader(socket.getInputStream());
catch (IOException e) {
throw new SessionStoppedException("No info");
while(connected){
try {
BufferedReader in = new BufferedReader(ins);
threadMessage("Creating sax builder");
documentBuilder = new SAXBuilder(true);
threadMessage("Building document");
Document doc = documentBuilder.build(in);
System.out.println("Received: " + doc.toString());
// If there are no well-formedness or validity errors,
// then no exception is thrown.
System.out.println(doc + " is valid.");
System.out.println(doc.getRootElement().getName());
// indicates a well-formedness or validity error
catch (JDOMException e) {
System.out.println( "is not valid.");
System.out.println(e.getMessage());
catch (IOException e) {
System.out.println("Could not check " );
System.out.println(" because " + e.getMessage());
catch(Exception e){
threadMessage("Error: " + e);
public void threadMessage(String message){
System.out.println(threadName + "(" + id + ")" + ": " + message);
}Thanks in advance.
Cheers,
JonasJonas.Nielsen wrote:
I've been instructed, that there is no way to send a end of file.
What would probably help would be to send the size of the serialized document before sending the actual document. But how is that done?First, you should probably be using the stream directly, not wrapping it in a Writer, so you can write byte-oriented data. Then, if you knew the size of the document ahead of time, you could send the number of bytes as a long, followed by the document. If you don't know the number of bytes ahead of time, you could come up with some chunking protocol, where you would write the size of the chunk, followed by the chunk bytes. A chunk size of 0 could indicate EOF.
The DataOutputStream/DataInputStream wrapper classes can be of assistance here. -
// Demonstrate InetAddress.
import java.net.*;
public class InetAddressTest
public static void main(String args[]) throws UnknownHostException
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("osborne.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for(int i = 0; i<SW.length; i++)
System.out.println(SW);
// I tried to run above program on my Ubuntu 10.11 in eclipse but got following errors
//The method getLocalHost() is undefined for the type InetAddress
//The method getByName(String) is undefined for the type InetAddress
//The method getAllByName(String) is undefined for the type InetAddress
//please tell me where i am wrong .I suspect you have a class of your own called InetAddress.
-
Hi all,
I am using an enhanced reciever determination for multiklient ruting.
In that context I need to know weather I shold pass the data to the D, Q og P system.
Is there any way that I can make a lookup or something in order to see which XI-system i am operation in?
So if XI-system = "D", then pass data on to D01CLNT900, If "P" then P01CLNT900 and so on.
Thanks -
/ThomasHi,
1) Write some Java code to get the hostname
package com.company.xi;
public class MappingFunctions {
public String getServerHostname()
throws UnknownHostException {
InetAddress myAddress = InetAddress.getLocalHost();
return myAddress.getHostName();
2) Package it in a JAR and load it into the IR as an imported archive.
3) Call it from your XSLT
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:mapping="java:com.company.xi.MappingFunctions">
<HostName><xsl:value-of select="mapping:getHostName()"/></HostName>
Also you can add the following code to get the system id.
// Get the system properties
String sysNr = (String) System.getProperty("SAPSYSTEM");
String sysName = (String) System.getProperty("SAPSYSTEMNAME");
Hope this will help you.
Regards
Aashish Sinha
PS : reward points if helpful
Edited by: Aashish Sinha on May 28, 2008 11:10 AM -
Smtp mail client socket problem
As soon i enter the smtp server address (smtp.mail.yahoo.com) i get the following:
Exception in thread "main" java.net.UnknownHostException: smtp.mail.yahoo.com: smtp.mail.yahoo.com
at java.net.InetAddress.getAllByName0(InetAddress.java:1128)
at java.net.InetAddress.getAllByName0(InetAddress.java:1098)
at java.net.InetAddress.getAllByName(InetAddress.java:1061)
at java.net.InetAddress.getByName(InetAddress.java:958)
at MailTest.<init>(MailTest.java:20)
at MailTest.main(MailTest.java:97)
Java Result: 1
BUILD SUCCESSFUL (total time: 11 seconds)
import java.util.*;
import java.net.*;
import java.io.BufferedReader;
import java.io.*;
public class MailTest
String from;
String to;
String smtp; //smtp.mail.yahoo.com
String hostName;
BufferedReader brin;
PrintWriter pwout;
String communication;
public MailTest() throws UnknownHostException,IOException
readMailData();
Socket s=new Socket(InetAddress.getByName(smtp), 25);
//tried also smtp.plus.mail.yahoo4.akadns.net and with the
//corresponding ip
hostName=InetAddress.getLocalHost().getHostName();
brin=new BufferedReader(new InputStreamReader(s.getInputStream()));
pwout=new PrintWriter(s.getOutputStream());
receive();
send("HELO "+ hostName);
receive();
send("MAIL FROM: <"+from+">");
receive();
send("DATA");
receive();
send(readMessageBody());
send(".");
receive();
s.close();
private void receive() throws IOException
System.out.println("Incoming Communication");
System.out.println("-----------------------------------------");
while (!(communication=brin.readLine()).equals(null))
System.out.println(communication);
System.out.println("-----------------------------------------");
private void send(String s) throws IOException
System.out.println("Outcoming Communication");
System.out.println(s);
pwout.write(s);
pwout.flush();
System.out.println("-----------------------------------------");
private String readMessageBody() throws IOException
String q="";
String msgBuffer="";
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("--------------Message--Body--------------");
System.out.println("enter -Enter-quit-Enter- to exit");
System.out.print(">");
q=in.readLine();
while (!q.equals("quit"));
msgBuffer+=q;
System.out.print(">");
q=in.readLine();
System.out.println("-----------------------------------------");
return msgBuffer;
private void readMailData() throws IOException
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
System.out.println("From: ");
from=in.readLine().trim();
System.out.println("To: ");
to=in.readLine().trim();
System.out.println("SMTP server: ");
smtp=in.readLine();
public static void main(String[] args) throws UnknownHostException, IOException
MailTest mt=new MailTest();
}I would say you have a DNS problem, or perhaps you aren't connected to the Internet. Can you ping smtp.mail.yahoo.com? or at least can ping resolve the name?
-
Clarification Regarding swings
Can you suggest me why this exception is coming in Swings??
java.lang.ArrayIndexOutOfBoundsException: 1
at javax.swing.text.BoxView.layoutMajorAxis(Unknown Source)
at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
at javax.swing.text.BoxView.layout(Unknown Source)
at javax.swing.text.BoxView.setSize(Unknown Source)
at javax.swing.text.WrappedPlainView.setSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextAreaUI.getPreferredSize(Unknown Sourc
e)
at javax.swing.JComponent.getPreferredSize(Unknown Source)
at javax.swing.JTextArea.getPreferredSize(Unknown Source)
at javax.swing.ScrollPaneLayout.layoutContainer(Unknown Source)
at java.awt.Container.layout(Unknown Source)
at java.awt.Container.doLayout(Unknown Source)
at java.awt.Container.validateTree(Unknown Source)
at java.awt.Container.validate(Unknown Source)
at javax.swing.RepaintManager.validateInvalidComponents(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
n Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at com.deceval.siidj.utilityclasses.ExceptionHandlingEventQueue.dispatch
Event(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
ERROR - ExceptionHandlingEventQueue.dispatchEvent(?) | com.deceval.siidj.utility
classes.ExceptionHandlingEventQueue@1082277
java.lang.ArrayIndexOutOfBoundsException: 1
at javax.swing.text.BoxView.layoutMajorAxis(Unknown Source)
at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
at javax.swing.text.BoxView.layout(Unknown Source)
at javax.swing.text.BoxView.setSize(Unknown Source)
at javax.swing.text.WrappedPlainView.setSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(Unknown Source)
at javax.swing.plaf.basic.BasicTextAreaUI.getPreferredSize(Unknown Sourc
e)
at javax.swing.JComponent.getPreferredSize(Unknown Source)
at javax.swing.JTextArea.getPreferredSize(Unknown Source)
at javax.swing.ScrollPaneLayout.layoutContainer(Unknown Source)
at java.awt.Container.layout(Unknown Source)
at java.awt.Container.doLayout(Unknown Source)
at java.awt.Container.validateTree(Unknown Source)
at java.awt.Container.validate(Unknown Source)
at javax.swing.RepaintManager.validateInvalidComponents(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknow
n Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at com.deceval.siidj.utilityclasses.ExceptionHandlingEventQueue.dispatch
Event(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)Thank you Darryl.Burke for your quick response,
I am attaching my code.I have done same thinng which you have assested me.But the problems still persist.Code is,.......
package com.deceval.siidj.siidtareasautomaticas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import org.apache.log4j.Logger;
import com.deceval.siidj.securityentcmd.SecurityEntCmdConstants;
import com.deceval.siidj.securityinterfaceobjects.NUMEROS_TABLASOBJ;
import com.deceval.siidj.siidframework.CustomErrorException;
import com.deceval.siidj.siidframework.FileObj;
import com.deceval.siidj.siidframework.LOG_TRANSFERENCIAOBJ;
import com.deceval.siidj.siidframework.ListElement;
import com.deceval.siidj.siidframework.MailProcesosAutomaticosObj;
import com.deceval.siidj.siidframework.SIIDExceptionUtil;
import com.deceval.siidj.siidframework.SIIDFrameworkConstants;
import com.deceval.siidj.siidframework.ServiceLocator;
import com.deceval.siidj.siidresults.CmpLeerLogTransferencia_OutputParams;
import com.deceval.siidj.siidresults.LeerNumeros_1_Tabla_OutputParams;
import com.deceval.siidj.siidtareasautomaticas_client.ClaseBaseMasivoObj;
import com.deceval.siidj.siidtareasautomaticas_client.TareasAutomaticasObj;
import com.deceval.siidj.siidwinutilities.SIIDCommonWin;
import com.deceval.siidj.siidwinutilities.SIIDWinUtilitiesConstants;
import com.deceval.siidj.utilityclasses.FechaDomainConverter;
import com.deceval.siidj.utilityclasses.IntegerConverter;
import com.deceval.siidj.utilityclasses.MiniFramework;
import com.deceval.siidj.utilityclasses.SIIDDateField;
import com.deceval.siidj.utilityclasses.SIIDFileChooser;
import com.deceval.siidj.utilityclasses.SIIDTextField;
import com.deceval.siidj.utilityclasses.TextDataConverter;
import com.gtl.ftoj.framework.DateFormat;
import com.gtl.ftoj.framework.DateTimeData;
import com.gtl.ftoj.framework.ForteFile;
import com.gtl.ftoj.framework.TextData;
import com.jgoodies.binding.adapter.BasicComponentFactory;
import com.jgoodies.binding.value.ValueModel;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
* class OperacionBcoRepAutomaticoWin which extends SIIDCommonWin
* @author GoldStone
* @version 2.0
public class OperacionBcoRepAutomaticoWin extends SIIDCommonWin {
private static final long serialVersionUID = 1L;
private CellConstraints cc = null;
private static Logger mLog = Logger
.getLogger(OperacionBcoRepAutomaticoWin.class);
private CTLOperacionBcoRepAutomaticoWin theCt;
private JTextArea logEnvioTxtTa;
private TareasAutomaticasObj TareasAutomaticasTIDISSvc;
private ForteFile LocalFileSystem;
private JButton btnOcultarBtn;
private JButton btnBorrarLogBtn;
private JButton brnGrabarLogBtn;
private JButton btnTerminarProcesoBtn;
private JComponent panel;
private ArrayList<ForteFile> files;
private Timer timer;
* constructs a new <OperacionBcoRepAutomaticoWin> object
public OperacionBcoRepAutomaticoWin() {
super();
cc = new CellConstraints();
theCt = new CTLOperacionBcoRepAutomaticoWin();
initialize();
theCt.setHabilitado(false);
theCt.setContador(60);
theCt.setRunning(false);
cargaConfiguracion();
theCt.setOpcSecuencia(true);
theCt.setOpcPrimeroSLuegoRs(true);
theCt.setOpcOrdenGrabacion(false);
theCt.setOpcSrecibido(true);
TareasAutomaticasTIDISSvc = TareasAutomaticasObj.getInstance();
mLog.info("Directorio Local");
mLog.info(theCt.getDirectorioEntrada());
mLog.info("Directorio Remoto");
mLog.info(theCt.getDirectorioRemoto());
try {
theCt.getFechaCambioDdf().setValue(theCt.setCurrentServerSO());
} catch (RemoteException e) {
SIIDExceptionUtil.unwrap(e);
for (int i = 0; i < theCt.getNumero_replicas(); i++) {
ClaseBaseMasivoObj item = new ClaseBaseMasivoObj();
theCt.getOpS().add(item);
theCt.getOpS().get(i).setTipoDeEstructura(14);
theCt.getOpS().get(i).estableceEstructurasAUsar();
for (int i = 0; i < theCt.getNumero_replicas(); i++) {
ClaseBaseMasivoObj item = new ClaseBaseMasivoObj();
theCt.getOpR().add(item);
theCt.getOpR().get(i).setTipoDeEstructura(15);
theCt.getOpR().get(i).estableceEstructurasAUsar();
window.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(getInstance(),
screenLanguageCat.getMessageCatalogString("10003038"),
"Question", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
theCt.setTERMINANDO(true);
theCt.setRunning(false);
timer.cancel();
window.dispose();
} else {
window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
window.setTitle(screenLanguageCat.getMessageCatalogString("10003246"));
* To initialize the window
private void initialize() {
panel = this.buildPanel();
logEnvioTxtTa.setEditable(false);
btnOcultarBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("10003041"));
btnBorrarLogBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("10003042"));
brnGrabarLogBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("10003043"));
btnTerminarProcesoBtn.setToolTipText(screenLanguageCat.getMessageCatalogString("100092"));
* Used to build the components on the TabbedPane
* @return JComponent
public JComponent buildPanel() {
PanelBuilder operacionBursatilGrd = new PanelBuilder(new FormLayout(
"fill:pref:grow", "fill:pref:grow"));
operacionBursatilGrd.add(logEnvioTxtPanel("fill:350dlu:grow",
createArea(true, 0, new Dimension(200, 200))), cc.xy(1, 1));
return operacionBursatilGrd.getPanel();
* Used to create the TextArea on the JScrollPane
* @param lineWrap
* boolean
* @param columns
* int
* @param minimumSize
* Dimension
* @return JScrollPane
private JScrollPane createArea(boolean lineWrap, int columns,
Dimension minimumSize) {
ValueModel logEnvioTxtModel = theCt.getPresentModel().getBufferedModel("logEnvioTxt");
TextDataConverter logEnvioTxtConv = new TextDataConverter(logEnvioTxtModel);
logEnvioTxtTa = MiniFramework.getTextArea(logEnvioTxtConv);
JScrollPane pane = new JScrollPane();
pane.setViewportView(logEnvioTxtTa);
pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
logEnvioTxtTa.setBorder(new CompoundBorder(new LineBorder(Color.GRAY),
new EmptyBorder(1, 3, 1, 1)));
logEnvioTxtTa.setLineWrap(lineWrap);
logEnvioTxtTa.setWrapStyleWord(true);
logEnvioTxtTa.setColumns(columns);
if (minimumSize != null) {
logEnvioTxtTa.setMinimumSize(new Dimension(150, 200));
return pane;
* Used to build the components on the logEnvioTxtPanel
* @param columnSpec
* String
* @param area
* JScrollPane
* @return JComponent
private JComponent logEnvioTxtPanel(String columnSpec, JScrollPane area) {
FormLayout layout = new FormLayout(columnSpec,
"pref,pref,pref,fill:150dlu:grow,2dlu,pref");
PanelBuilder builder = new PanelBuilder(layout);
builder.setDefaultDialogBorder();
builder.add(fechaCodigoPlazaPnl(), cc.xy(1, 2));
builder.add(area, cc.xy(1, 4));
builder.add(btnOcultarPanel(), cc.xy(1, 6, "center,center"));
return builder.getPanel();
* Used to build the components on the fechaCodigoPlazaPnl
* @return JComponent
private JComponent fechaCodigoPlazaPnl() {
PanelBuilder CodigoPlazaGrd = new PanelBuilder(new FormLayout(
"pref,pref", "pref"));
CodigoPlazaGrd.add(fechaCambioGrfPanel(), cc.xy(1, 1, "center,top"));
CodigoPlazaGrd.add(codigoPlazaGrdPanel(), cc.xy(2, 1));
return CodigoPlazaGrd.getPanel();
* Used to add the components on the fechaCambioGrfPanel
* @return JComponent
private JComponent fechaCambioGrfPanel() {
FormLayout formLayout = new FormLayout("2dlu,pref,2dlu,60dlu",
"pref,2dlu,pref,2dlu,pref");
PanelBuilder fechaCambioGrfPnl = new PanelBuilder(formLayout);
JLabel fechaCambioTxgLbl = MiniFramework.getLabel(screenLanguageCat
.getMessageCatalogString("1000166"));
ValueModel fechaCambioDdfModel = theCt.getPresentModel()
.getBufferedModel("fechaCambioDdf");
FechaDomainConverter fechaCambioDdfConv = new FechaDomainConverter(
fechaCambioDdfModel);
SIIDDateField fechaCambioDdfTf = new SIIDDateField(fechaCambioDdfConv);
setWidgetState(fechaCambioDdfTf, FS_DISABLED);
JLabel numero_replicasLbl = MiniFramework.getLabel(screenLanguageCat
.getMessageCatalogString("10003044"));
ValueModel numero_replicasModel = theCt.getPresentModel()
.getBufferedModel("numero_replicas");
IntegerConverter numero_replicasConv = new IntegerConverter(
numero_replicasModel);
SIIDTextField numero_replicasTf = MiniFramework
.getNumericTextField(numero_replicasConv);
numero_replicasTf.setHorizontalAlignment(SwingConstants.RIGHT);
setWidgetState(numero_replicasTf, FS_DISABLED);
fechaCambioGrfPnl.add(fechaCambioTxgLbl, cc.xy(2, 1));
fechaCambioGrfPnl.add(fechaCambioDdfTf, cc.xy(4, 1));
fechaCambioGrfPnl.add(numero_replicasLbl, cc.xy(2, 3));
fechaCambioGrfPnl.add(numero_replicasTf, cc.xy(4, 3));
ValueModel verultimalineaModel = theCt.getPresentModel()
.getBufferedModel("verUltimaLinea");
JCheckBox verultimalineaChb = BasicComponentFactory.createCheckBox(
verultimalineaModel, screenLanguageCat
.getMessageCatalogString("10003239"));
verultimalineaChb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
theCt.getTrigger().triggerCommit();
if (theCt.isVerUltimaLinea()) {
logEnvioTxtTa.setCaretPosition(logEnvioTxtTa.getText()
.length());
fechaCambioGrfPnl.add(verultimalineaChb, cc.xyw(2, 5, 3));
return fechaCambioGrfPnl.getPanel();
* It adds the components to the panel
* @return JComponent
private JComponent codigoPlazaGrdPanel() {
FormLayout formlayout = new FormLayout("pref", "pref,pref,pref,pref");
PanelBuilder fechadeProcesoPnl = new PanelBuilder(formlayout);
ValueModel opcOrdenGrabacionModel = theCt.getPresentModel()
.getBufferedModel("opcOrdenGrabacion");
JCheckBox opcOrdenGrabacionChb = BasicComponentFactory.createCheckBox(
opcOrdenGrabacionModel, screenLanguageCat
.getMessageCatalogString("10003247"));
opcOrdenGrabacionChb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
theCt.getTrigger().triggerCommit();
enviaMensajeCorreo(SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
new TextData("CAMBIA configuraci�n por orden de grabacion modificado, nuevo valor: ")
.concat(theCt.isOpcOrdenGrabacion()));
ValueModel opcPrimeroSLuegoRsModel = theCt.getPresentModel().getBufferedModel("opcPrimeroSLuegoRs");
JCheckBox opcPrimeroSLuegoRsChb = BasicComponentFactory.createCheckBox(
opcPrimeroSLuegoRsModel, screenLanguageCat
.getMessageCatalogString("10003248"));
opcPrimeroSLuegoRsChb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
theCt.getTrigger().triggerCommit();
enviaMensajeCorreo(SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
new TextData("CAMBIA configuraci�n primero S luego R modificado, nuevo valor: ")
.concat(theCt.isOpcPrimeroSLuegoRs()));
ValueModel opcSecuenciaModel = theCt.getPresentModel()
.getBufferedModel("opcSecuencia");
JCheckBox opcSecuenciaChb = BasicComponentFactory.createCheckBox(
opcSecuenciaModel, screenLanguageCat
.getMessageCatalogString("10003249"));
opcSecuenciaChb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
theCt.getTrigger().triggerCommit();
enviaMensajeCorreo(
SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
new TextData(
"CAMBIA configuraci�n por orden de secuencia, nuevo valor:")
.concat(theCt.isOpcSecuencia()));
ValueModel opcSrecibidoModel = theCt.getPresentModel()
.getBufferedModel("opcSrecibido");
JCheckBox opcSrecibidoChb = BasicComponentFactory.createCheckBox(
opcSrecibidoModel, screenLanguageCat
.getMessageCatalogString("10003250"));
opcSrecibidoChb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
theCt.getTrigger().triggerCommit();
enviaMensajeCorreo(
SIIDFrameworkConstants.EVTBANREP_CAMBIACONFIGURACION,
new TextData(
"CAMBIA configuraci�n esperar S de un E enviado, nuevo valor:")
.concat(theCt.isOpcSrecibido()));
fechadeProcesoPnl.add(opcOrdenGrabacionChb, cc.xy(1, 1));
fechadeProcesoPnl.add(opcPrimeroSLuegoRsChb, cc.xy(1, 2));
fechadeProcesoPnl.add(opcSecuenciaChb, cc.xy(1, 3));
fechadeProcesoPnl.add(opcSrecibidoChb, cc.xy(1, 4));
return fechadeProcesoPnl.getPanel();
* It adds the buttons to the panel
* @return JComponent
private JComponent btnOcultarPanel() {
FormLayout form3 = new FormLayout(
"2dlu,pref,2dlu,pref,2dlu,pref,2dlu,pref,2dlu",
"3dlu,pref,3dlu");
PanelBuilder btnOcultarPnl = new PanelBuilder(form3);
btnOcultarBtn = MiniFramework.getButton(screenLanguageCat
.getMessageCatalogString("10003240"));
btnOcultarBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
window.setVisible(false);
close();
btnBorrarLogBtn = MiniFramework.getButton(screenLanguageCat
.getMessageCatalogString("10003241"));
btnBorrarLogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (theCt.getLogEnvioTxt().getActualSize() == 0) {
// continue;
borrarLog();
btnTerminarProcesoBtn = MiniFramework.getButton(screenLanguageCat
.getMessageCatalogString("10003242"));
btnTerminarProcesoBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (JOptionPane.showConfirmDialog(getInstance(),
screenLanguageCat.getMessageCatalogString("10003038"),
"Question", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
theCt.setTERMINANDO(true);
theCt.setRunning(false);
timer.cancel();
window.dispose();
brnGrabarLogBtn = MiniFramework.getButton(screenLanguageCat
.getMessageCatalogString("10003243"));
brnGrabarLogBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
grabarLog();
btnTerminarProcesoBtn.setMargin(new Insets(1, 4, 1, 4));
btnOcultarPnl.add(btnOcultarBtn, cc.xy(2, 2));
btnOcultarPnl.add(btnBorrarLogBtn, cc.xy(4, 2));
btnOcultarPnl.add(brnGrabarLogBtn, cc.xy(6, 2));
btnOcultarPnl.add(btnTerminarProcesoBtn, cc.xy(8, 2));
return btnOcultarPnl.getPanel();
* Method addLog
* @param str
* Textdata
public void addLog(TextData str) {
addLog(str, true, 0);
* Method addLog
* @param str
* TextData
* @param confecha
* boolean
public void addLog(TextData str, boolean confecha) {
addLog(str, confecha, 0);
* Method addLog
* @param str
* TextData
* @param confecha
* boolean
* @param hilo
* int
public void addLog(TextData str, boolean confecha, int hilo) {
// TODO topline = <logEnvioTxt>.topline ;
// theCt.setTopline(logEnvioTxtTa.topline);
if (hilo > 0) {
theCt.getLogEnvioTxt().concat("(");
theCt.getLogEnvioTxt().concat(hilo);
theCt.getLogEnvioTxt().concat(")");
if (confecha) {
theCt.getLogEnvioTxt().concat(theCt.getNow().setCurrent());
theCt.getLogEnvioTxt().concat(":");
theCt.getLogEnvioTxt().concat(str);
theCt.getLogEnvioTxt().concat(System.getProperty("line.separator"));
theCt.setLogEnvioTxt(theCt.getLogEnvioTxt());
//theCt.getPresentModel().setBean(null);
theCt.getPresentModel().setBean(theCt);
hastaLaUltimaLinea();
// EJBHelper ejbHelper = new EJBHelper();
// Please copy this Helper class to the current directory
// ejbHelper.publishNews("hastaLaUltimaLinea","");
* until It completes Line
public void hastaLaUltimaLinea() {
if (theCt.isVerUltimaLinea()) {
// logEnvioTxtTa.setSelectionStart(logEnvioTxtTa.getText().length());
logEnvioTxtTa.setCaretPosition(logEnvioTxtTa.getText().length());
} else {
// logEnvioTxtTa.setCaretPosition(logEnvioTxtTa);
// logEnvioTxtTa.setSelectionStart(logEnvioTxtTa.getText().length());
* To erase LoG
public void borrarLog() {
int resp = JOptionPane.showConfirmDialog(getInstance(),
screenLanguageCat.getMessageCatalogString("10003039"),
"Question", JOptionPane.YES_NO_OPTION);
if (resp == JOptionPane.YES_OPTION) {
theCt.getLogEnvioTxt().clear();
theCt.getPresentModel().setBean(null);
theCt.getPresentModel().setBean(theCt);
* Method getInstance
* @return <OperacionBcoRepAutomaticoWin>
public OperacionBcoRepAutomaticoWin getInstance() {
return this;
* load Configuration
public void cargaConfiguracion() {
theCt.setDirectorioEntrada("c:\\BVC\\entrada");
theCt.setDirectorioNoProcesados("c:\\BVC\\noprocesados");
theCt.setDirectorioProcesados("c:\\BVC\\procesados");
theCt.setDirectorioSalida("c:\\BVC\\salida");
theCt.setDirectorioTemporal("c:\\BVC\\temporal");
InetAddress localhost = null;
try {
localhost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
mLog.info(e.getMessage(), e);
try {
List temp = null;
temp = theCt
.operacionBcoRepAutomaticoWin_runSql(
theCt.SecurityClientSvc.LoginUser.getUserLogin()
.trim(), localhost.getHostName()
.toUpperCase(),
theCt.SecurityClientSvc.LoginUser
.getUserProfileId().trim());
if (temp != null) {
if (temp.size() == 1) {
Map returnRow = (Map) temp.get(0);
theCt.setDirectorioEntrada(String.valueOf(returnRow
.get("carpeta_entrada")));
theCt.setDirectorioSalida(String.valueOf(returnRow
.get("carpeta_salida")));
theCt.setDirectorioTemporal(String.valueOf(returnRow
.get("carpeta_temporal")));
theCt.setDirectorioProcesados(String.valueOf(returnRow
.get("carpeta_procesados")));
theCt.setDirectorioNoProcesados(String.valueOf(returnRow
.get("carpeta_no_procesados")));
theCt.setNumero_replicas(Integer.parseInt(returnRow.get(
"numero_replicas").toString()));
theCt.setHabilitado(true);
} catch (Exception e) {
mLog
.info(screenLanguageCat.getMessageCatalogString("10006723"));
mLog.info(e.getMessage());
JOptionPane.showMessageDialog(getInstance(), new TextData(
screenLanguageCat.getMessageCatalogString("1003937")
.concat(e.getMessage())));
if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
theCt.pAlErrors.remove(0);
* the data base the bags
* @return ArrayList<ListElement>
public ArrayList<ListElement> cargaDropBolsas() {
// Jos� Miguel de Priego
// Agosto 03, 2004
// Se lee desde la base de datos las bolsas
ArrayList<NUMEROS_TABLASOBJ> arreglo_bolsas = new ArrayList<NUMEROS_TABLASOBJ>();
int wnumero_filas_afectadas = 0;
ArrayList<NUMEROS_TABLASOBJ> arreglo_numeros = null;
try {
LeerNumeros_1_Tabla_OutputParams obj = null;
obj = theCt.listadeNumeros1TablaSO(46, wnumero_filas_afectadas);
arreglo_numeros = obj.retVal;
wnumero_filas_afectadas = obj.prows;
} catch (RemoteException e) {
SIIDExceptionUtil.unwrap(e);
ArrayList<ListElement> dropBolsas = null;
if (arreglo_numeros != null) {
NUMEROS_TABLASOBJ i = new NUMEROS_TABLASOBJ();
int size = 0;
if (arreglo_numeros != null) {
size = arreglo_numeros.size();
for (int j = 0; j < size; j++) {
i = (NUMEROS_TABLASOBJ) arreglo_numeros.get(j);
// si es 1 es bolsa, o tiene como mecanismo bursatil
if (((i.getIndicador_4() == 1) && ("OK".equals(i
.getIndicador_1())))
|| (i.getCodigo_numerico() == 0)) {
arreglo_bolsas.add(i);
dropBolsas = theCt.getToolSO().deNumParametrosAListElement(
arreglo_bolsas);
if (dropBolsas != null) {
for (ListElement each : dropBolsas) {
// task.part.logMgr.PutLine( TextData("-> ").concat(
// each.integerValue).concat( " -> ").concat( each.textvalue
arreglo_bolsas = null;
arreglo_numeros = null;
return dropBolsas;
* It consults Encripcion Parameter
public void consultaParametroEncripcion() {
// MFBI-JUNIO-4-1-2:2005/06/21 Metodo nuevo
try {
theCt.setParametroEncripcion("S");
theCt.setParametroEncripcion(theCt.operacionBcoRepAutomaticoWin_runSql1());
} catch (Exception e) {
addLog(new TextData(screenLanguageCat.getMessageCatalogString("10006724")));
addLog(new TextData(e.getMessage()));
if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
theCt.pAlErrors.remove(0);
* Method copy
* @param proceso
* String
* @param NombreArchivo
* String
* @param replica
* String
* @return String
public String copiar2(String proceso, String NombreArchivo, int replica) {
// Jose Miguel de Priego Julio 09, 2004
// Se agrega la variable es encriptada para
// manejo de archivos encriptados
boolean esEncriptada = false;
TextData nombreDirectorioArchivoDdf = new TextData(NombreArchivo);
if (nombreDirectorioArchivoDdf.moveToString(
SecurityEntCmdConstants.FILE_SECURE_EXTENSION, true)) {
if (nombreDirectorioArchivoDdf.getOffset() == nombreDirectorioArchivoDdf
.getActualSize()) {
esEncriptada = true;
nombreDirectorioArchivoDdf.setOffset(0);
try {
if (!esEncriptada) {
ejecutarCopia(NombreArchivo, replica);
} else {
String dir = theCt.defineDirectorioRemotoSO();
ForteFile f = new ForteFile();
f.setLocalName(nombreDirectorioArchivoDdf.getValue());
TextData fn = f.getLocalName();
if (fn.moveToLastChar("/")) {
fn.cutRange(0, fn.getOffset() + 1);
//TODO for verifying impact Prashanth 01/08/2008
return SIIDWinUtilitiesConstants.Empty_String;/*ServiceLocator.getInstance().getEntCmdServicesSO().moveDecriptedFile(proceso,
fn.getValue(), dir);*/// temp
} catch (Exception e) {
// TODO if(e.getreasonCode == OS_FE_FILEEXISTENCE ){
addLog(new TextData("Error Archivo no existe .."), true, replica);
addLog(new TextData(e.getMessage()), true, replica);
if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
theCt.pAlErrors.remove(0);
return SIIDWinUtilitiesConstants.Empty_String;
* To display the current window
public void display() {
theCt.setTERMINANDO(false);
// Recuperacion archivos E
theCt.setProcesoA(false);
// Envio de Archios S, R
theCt.setProcesoB(false);
theCt.setRunning(false);
int delay = 0;
int period = 1000;
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
if (theCt.getContador() % 30 == 0) {
theCt.setContador(0);
// Cada 2 minutos va el proceso de recuperacion de archivos E
// Cada 30 segundos va el proceso de envio de archivos R,S
if (theCt.getContador() == 0) {
if (!theCt.isProcesoA()) {
new Thread(){
public void run() {
recuperaOtrosArchivos(1);
}.start();
if (theCt.getContador() % 10 == 0){
theCt.getPresentModel().setBean(null);
theCt.getPresentModel().setBean(theCt);
if (theCt.getContador() % 30 == 15) {
if (!theCt.isProcesoB()) {
new Thread(){
public void run() {
preprocesa(1);
}.start();
theCt.setContador(theCt.getContador() + 1);
}, delay, period);
open(panel);
* To execute Copy
* @param pArchivo
* String
* @param replica
* int
* @return boolean
public boolean ejecutarCopia(String pArchivo, int replica) {
LocalFileSystem = new ForteFile();
// RemotoFileSystem : FileSystem = ServidorTareaSO.CreaProxy();
// localFileSystem.SetRemoteFS(remotoFileSystem);
// remotoFileSystem.SetRemoteFS(localFileSystem);
TextData remoteFile = null;
try {
remoteFile = theCt.getServidorTarea().estableceDirectorio(
SIIDFrameworkConstants.DIR_APLIC_CLIENTE,
theCt.SecurityClientSvc.LoginUser.getUserPath(),
theCt.pAppContext, theCt.pAlErrors);
} catch (RemoteException e) {
SIIDExceptionUtil.unwrap(e);
if (remoteFile != null) {
theCt.setDirectorioRemoto(remoteFile.getValue());
TextData directorioRemoto = null;
try {
directorioRemoto = new TextData(theCt.defineDirectorioRemotoSO());
} catch (RemoteException e1) {
SIIDExceptionUtil.unwrap(e1);
int NroCar = theCt.getToolSO().lenStr(directorioRemoto.getValue());
NroCar = NroCar - 1;
directorioRemoto = new TextData(theCt.getToolSO().subStr(
directorioRemoto.getValue(), 1, NroCar));
// localFileSystem.SetLocalDir( theCt.getDirectorioEntrada() );
// localFileSystem.SetRemoteDir( directorioRemoto );
ArrayList<TextData> ListaArchivos = new ArrayList<TextData>();
try {
while (true) {
ListaArchivos.clear();
ListaArchivos.add(new TextData(pArchivo));
File srcPath = new File(LocalFileSystem.getPortableName(true,false).getValue());
try {
copyFile(srcPath);
} catch (IOException e) {
mLog.error(e.getMessage(), e);
LocalFileSystem = null;
// RemotoFileSystem = null;
ListaArchivos = null;
return true;
} catch (Exception e) {
addLog(new TextData("*EjecutarCopia: ").concat(e.getMessage()),
true, replica);
if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
theCt.pAlErrors.remove(0);
// // return false;
nsegundos(5);
return true;
* It establishes the directories on who he worked
* @param srcPath
* File
* @throws IOException
@SuppressWarnings( { "unused", "unchecked" })
public void copyFile(File srcPath) throws IOException {
ArrayList fileList = new ArrayList();
InputStream in = null;
try {
if (srcPath.isDirectory()) {
String[] files = srcPath.list();
for (int i = 0; i < files.length; i++) {
FileObj fObj = new FileObj();
File pFile = new File(srcPath, files);
in = new FileInputStream(pFile);
int size = (int) pFile.length();
byte[] buf = new byte[size];
int len = 0;
while ((len = in.read(buf)) > 0) {
fObj.setName(files[i]);
fObj.setContent(buf);
fileList.add(fObj);
in.close();
theCt.pushFiles(fileList, theCt.getDirectorioRemoto());
} else {
if (!srcPath.exists()) {
mLog.info("File or directory does not exist.");
if (srcPath.isFile()) {
in = new FileInputStream(srcPath);
int size = (int) srcPath.length();
byte[] buf = new byte[size];
int len;
FileObj fObj = new FileObj();
while ((len = in.read(buf)) > 0) {
fObj.setName(srcPath.getName());
fObj.setContent(buf);
fileList.add(fObj);
in.close();
theCt.pushFiles(fileList, theCt.getDirectorioRemoto());
} catch (Exception e) {
mLog.error(e);
} finally {
in.close();
* It sends Message Mail
* @param evento
* int
* @param obs
* TextData
public void enviaMensajeCorreo(int evento, TextData obs) {
try {
if (theCt.getEnvios() == null || theCt.getEnvios().size() == 0) {
theCt.setEnvios(TareasAutomaticasTIDISSvc.a_ObtieneParametrosCorreo(2, theCt.pAppContext,theCt.pAlErrors));
} catch (Exception e) {
addLog(new TextData("enviamensajecorreo(1): ").concat(e.getMessage()));
if (theCt.pAlErrors != null && theCt.pAlErrors.size() > 0) {
theCt.pAlErrors.remove(0);
theCt.setEnvios(null);
if (theCt.getEnvios() == null) {
return;
MailProcesosAutomaticosObj each = null;
int size = 0;
if (theCt.getEnvios() != null) {
size = theCt.getEnvios().size();
for (int i = 0; i < size; i++) {
each = (MailProcesosAutomaticosObj) theCt.getEnvios().get(i);
if ((each.getEstado() == 1) && (each.getEvento() == evento)) {
try {
each.setMensaje(obs.getTextValue().getValue());
TareasAutomaticasTIDISSvc.a_EnviaMensajeCorreo(each);
} catch (Exception e) {
addLog(new TextData("enviamensajecorreo(2): ").concat(e
.getMessage()));
if (theCt.pAlErrors != null && theCt.pAlErrors.size -
Help with simple bidding program
I have a BiddingServer and a BiddingClient, Everytime a client connects it connects twice for some reason, and shows "New Bidder Accepted" twice... Can't work out why, any help appreciated.... I dont know whether the problem is here or in the client and i appreciate its looong so if no one spots a problem here ill post the client....
import java.io.*;
import java.net.*;
import java.text.DecimalFormat;
import java.util.*;
public class BiddingServer
private static ServerSocket servSocket;
private static final int PORT = 1234;
public static Scanner keyboard = new Scanner(System.in);
public static String itemDescripOne = "TV", itemCodeOne = "123";
public static String itemDescripTwo = "Toaster", itemCodeTwo = "321";
public static float itemPriceOne = 100, itemPriceTwo = 200;
public static Calendar deadlineOne;
public static Calendar deadlineTwo;
private static int clientCount =0;
public static void main(String[] args)throws IOException
Calendar start = Calendar.getInstance();
int date = start.get(Calendar.DATE);
int month = start.get(Calendar.MONTH);
int year = start.get(Calendar.YEAR);
System.out.printf("\nEnter First Item's finishing bid time");
String timeString = BiddingServer.keyboard.nextLine();
String hourString = timeString.substring(0,2);
int hour = Integer.parseInt(hourString);
String minString = timeString.substring(3,5);
int minute = Integer.parseInt(minString);
BiddingServer.deadlineOne = Calendar.getInstance();//Set up Calendar object to hold deadline time...
BiddingServer.deadlineOne.set(year,month,date,hour,minute,0);
System.out.println("\nEnter Second Item's finishing bid time:\n");
String timeString1 = BiddingServer.keyboard.nextLine();
String hourString1 = timeString1.substring(0,2);
int hour1 = Integer.parseInt(hourString1);
String minString1 = timeString1.substring(3,5);
int minute1 = Integer.parseInt(minString1);
BiddingServer.deadlineTwo = Calendar.getInstance();//Set up Calendar object to hold deadline time...
BiddingServer.deadlineTwo.set(year,month,date,hour1,minute1,0);
System.out.println("Opening port...\n");
try
servSocket = new ServerSocket(PORT);
catch (IOException e)
System.out.println("\nUnable to set up port!");
System.exit(1);
do
Socket client = servSocket.accept();
clientCount++;
//Wait for client.
System.out.println("\nNew bidder accepted.\n");
ClientHandler handler = new ClientHandler(client, clientCount);
handler.start();
}while (true);
class ClientHandler extends Thread
private Socket client;
private Scanner input, keyboard;
private PrintWriter output;
int clientNumber;
public ClientHandler(Socket socket, int count) throws IOException
client = socket;
clientNumber = count;
keyboard = new Scanner(System.in);
input = new Scanner(client.getInputStream());
output = new PrintWriter(client.getOutputStream(),true);
public void run()
String userInput;
float price, priceTwo ;
output.println(BiddingServer.itemDescripOne);
output.println(BiddingServer.itemCodeOne);
output.println(getDateTime(BiddingServer.deadlineOne));
output.println(BiddingServer.itemDescripTwo);
output.println(BiddingServer.itemCodeTwo);
output.println(getDateTime(BiddingServer.deadlineTwo));
do
userInput = input.nextLine();
Calendar now = Calendar.getInstance();
if (userInput.startsWith("number of bidders"))
System.out.println("Number of Bidders Online " + clientNumber);
output.println(clientNumber);
else if ((userInput.startsWith(BiddingServer.itemCodeOne)) && (userInput.endsWith("Status")))
System.out.println("item price one");
output.println(BiddingServer.itemPriceOne);
if ((userInput.startsWith(BiddingServer.itemCodeOne)) && (userInput.endsWith("Status")) && (now.after(BiddingServer.deadlineOne)))
System.out.println("-1, bidding for item ended");
output.println("-1");
else if (userInput.startsWith(BiddingServer.itemCodeOne))
price = Float.parseFloat(userInput.substring(BiddingServer.itemCodeOne.length() +1));
if ((price > BiddingServer.itemPriceOne) && (now.before(BiddingServer.deadlineOne)))
//bidForItem();
System.out.println("Bid Accepted");
output.println("Bid Accepted");
BiddingServer.itemPriceOne = price;
else if (now.after(BiddingServer.deadlineOne))
System.out.println("Late Bid");
output.println("Late Bid");
else if ((price <= BiddingServer.itemPriceOne) && (now.before(BiddingServer.deadlineOne)))
System.out.println("Low Bid");
output.println("Low Bid");
if ((userInput.startsWith(BiddingServer.itemCodeTwo)) && (userInput.endsWith("Status")))
System.out.println("item price one");
output.println(BiddingServer.itemPriceOne);
else if ((userInput.startsWith(BiddingServer.itemCodeTwo)) && (userInput.endsWith("Status")) && (now.after(BiddingServer.deadlineTwo)))
System.out.println("-1, bidding for item ended");
output.println("-1");
else if (userInput.startsWith(BiddingServer.itemCodeTwo))
priceTwo = Float.parseFloat(userInput.substring(BiddingServer.itemCodeTwo.length() +1));
if ((priceTwo > BiddingServer.itemPriceTwo) && (now.before(BiddingServer.deadlineTwo)))
System.out.println("Bid Accepted");
output.println("Bid Accepted");
BiddingServer.itemPriceTwo = priceTwo;
else if (now.after(BiddingServer.deadlineTwo))
System.out.println("Late Bid");
output.println("Late Bid");
else if ((priceTwo <= BiddingServer.itemPriceTwo) && (now.before(BiddingServer.deadlineTwo)))
System.out.println("Low Bid");
output.println("Low Bid");
}while (true);
public String getDateTime(Calendar dateTime)
//Create DecimalFormat object to ensure 2 dec places...
DecimalFormat decFormat = new DecimalFormat("00");
//Now extract hours and minutes, each with 2 digits
//(i.e., with leading zeroes if needed)...
String hour2Digits =
decFormat.format(dateTime.get(Calendar.HOUR_OF_DAY));
String min2Digits =
decFormat.format(dateTime.get(Calendar.MINUTE));
return(dateTime.get(Calendar.DATE) + "/"
+ (dateTime.get(Calendar.MONTH)+1) + "/"
+ dateTime.get(Calendar.YEAR) + " "
+ hour2Digits + ":" + min2Digits);
}import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
public class BiddingClient extends JFrame implements ActionListener
private InetAddress host;
private final int PORT = 1234;
private Socket link;
private Scanner networkInput,keyboard;
private PrintWriter output;
private JPanel itemInfo, buttonPanel, comboPanel, headingPanel, selectItemPanel,personalPanel,biddingText;
private JLabel label1,label2,label3, label4, label,label5, labelCode, labelDescrip,
labelDeadline, labelPrice,bidStatus,label6,label7;
private JComboBox itemSelection;
private JButton bidButton, statusButton, noOfBiddersButton, quitButton;
private JTextField bid;
String [] code = new String [2];
String [] desc = new String [2];
String [] deadline = new String [2];
public static void main(String[] args) throws IOException
BiddingClient frame = new BiddingClient();
frame = new BiddingClient();
frame.setTitle("Welcome " + System.getProperty("user.name"));
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = (int)screenSize.getWidth();
int screenHeight = (int)screenSize.getHeight();
int frameWidth=430 ,frameHeight=300;
frame.setSize(frameWidth,frameHeight);
frame.setLocation((screenWidth-frameWidth)/2,
(screenHeight-frameHeight)/2);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
public BiddingClient () throws IOException
addWindowListener(
new WindowAdapter()
public void windowClosing(WindowEvent e)
if (link != null)
try
link.close();
catch (IOException ioEx)
System.out.println(
"\n*** Unable to close link!***\n");
System.exit(1);
System.exit(0);
try
host = InetAddress.getLocalHost();
catch(UnknownHostException uhEx)
System.out.println("\nHost ID not found!\n");
System.exit(1);
personalPanel = new JPanel(new FlowLayout());
setLayout(new BorderLayout());
label6 = new JLabel("Welcome... " + System.getProperty("user.name"));
label6.setFont (new Font("Edwardian Script ITC",Font.PLAIN,26));
personalPanel.add(label6, BorderLayout.CENTER);
personalPanel.setBackground(Color.lightGray);
add(personalPanel, BorderLayout.NORTH);
comboPanel = new JPanel(new BorderLayout());
//comboPanel.setBorder(BorderFactory.createLineBorder(Color.red));
itemSelection = new JComboBox();
comboPanel.add(itemSelection, BorderLayout.EAST);
itemSelection.addActionListener(this);
add(comboPanel, BorderLayout.NORTH);
selectItemPanel = new JPanel(new BorderLayout());
label5 = new JLabel("Please Select An Item From The List:");
selectItemPanel.add(label5, BorderLayout.CENTER);
add(selectItemPanel, BorderLayout.WEST);
headingPanel = new JPanel(new FlowLayout());
String myText4 = "<HTML><b><u>Information On Item</b></u>";
label = new JLabel(myText4);
headingPanel.add(label);
//headingPanel.setBorder(BorderFactory.createLineBorder(Color.white));
add(headingPanel, BorderLayout.CENTER);
comboPanel.add(headingPanel, BorderLayout.SOUTH);
comboPanel.add(selectItemPanel, BorderLayout.WEST);
comboPanel.add(personalPanel, BorderLayout.NORTH);
itemInfo = new JPanel(new GridLayout(6,1));
String myText = "<HTML><b><u>Description</b></u> : ";
label1 = new JLabel(myText);
itemInfo.add(label1);
labelDescrip = new JLabel();
labelDescrip.setFont (new Font("ComicSans",Font.PLAIN,12));
itemInfo.add(labelDescrip);
String myText1 = "<HTML><b><u>Code</b></u> : ";
label2 = new JLabel(myText1);
label2.setFont (new Font("Arial Narrow",Font.BOLD,13));
itemInfo.add(label2);
labelCode = new JLabel();
labelCode.setFont (new Font("ComicSans",Font.PLAIN,12));
itemInfo.add(labelCode);
String myText2 = "<HTML><b><u>Deadline</b></u> : ";
label3 = new JLabel(myText2);
itemInfo.add(label3);
labelDeadline = new JLabel();
labelDeadline.setFont (new Font("ComicSans",Font.PLAIN,12));
itemInfo.add(labelDeadline);
String myText3 = "<HTML><b><u>Price</b></u> : ";
label4 = new JLabel(myText3);
itemInfo.add(label4);
labelPrice = new JLabel("Click Status To View Price ");
labelPrice.setFont (new Font("ComicSans",Font.PLAIN,12));
itemInfo.add(labelPrice);
bidStatus = new JLabel("");
itemInfo.add(bidStatus);
add(itemInfo, BorderLayout.CENTER);
biddingText = new JPanel(new FlowLayout());
bid = new JTextField("Enter Bid Here",10);
bid.addActionListener(this);
biddingText.add(bid);
add(biddingText, BorderLayout.SOUTH);
bidButton = new JButton("Place Bid");
biddingText.add(bidButton);
bidButton.addActionListener(this);
statusButton = new JButton("Status");
biddingText.add(statusButton);
statusButton.addActionListener(this);
noOfBiddersButton = new JButton("No. Of Bidders");
biddingText.add(noOfBiddersButton);
noOfBiddersButton.addActionListener(this);
quitButton = new JButton("Quit");
biddingText.add(quitButton);
quitButton.addActionListener(this);
add(biddingText, BorderLayout.SOUTH);
link = new Socket(host, PORT);
networkInput = new Scanner(link.getInputStream());
output = new PrintWriter(link.getOutputStream(),true);
keyboard = new Scanner(System.in);
getItems();
System.out.println("haha");
public void getItems()
for (int i = 0; i <2 ; i++)
desc[i] = networkInput.nextLine();
code[i] = networkInput.nextLine();
deadline[i] = networkInput.nextLine();
itemSelection.addItem(code);
public void actionPerformed(ActionEvent e)
if (e.getSource()== itemSelection)
labelDescrip.setText(desc[itemSelection.getSelectedIndex()]);
labelCode.setText(code[itemSelection.getSelectedIndex()]);
labelDeadline.setText(deadline[itemSelection.getSelectedIndex()]);
}else if ((e.getSource()== bidButton) || (e.getSource() == bid))
output.println(labelCode.getText() + " " + bid.getText());
JOptionPane.showMessageDialog(null,networkInput.nextLine());
//bidStatus.setText(networkInput.nextLine());
//System.out.println(bidStatus.getText());
}else if (e.getSource()== statusButton)
output.println(labelCode.getText()+ "Status");
labelPrice.setText(networkInput.nextLine());
if (labelPrice.getText().equals("-1"))
labelPrice.setText("Bidding Time Is Up On This Item");
else
labelPrice.setVisible(true);
}else if (e.getSource()== noOfBiddersButton)
output.println("number of bidders");
JOptionPane.showMessageDialog(null,"Number Of Bidders Online\n "+ networkInput.nextLine()
,"Information", JOptionPane.INFORMATION_MESSAGE);
}else if (e.getSource() == quitButton)
try
JOptionPane.showMessageDialog(this,"Closing down connection...",
"Warning", JOptionPane.WARNING_MESSAGE);
System.out.println("*Connection Closed*");
link.close();
System.exit(0);
catch(IOException ioex)
System.out.println("***Disconnection problem!***");
System.exit(1);
Maybe you are looking for
-
Some advice - buying a MacBook Air
Hi, I am planning to buy a MacBook Air (13" version), and have some questions which I would like some help! 1. Performance/Upgrades I am trying to figure out whether I should get the Processor (i5 to i7) and/or RAM (4GB to 8GB) upgrades - is it worth
-
ZMM Profile on IOS 7.1 will not install with ZMM 3.0
Anybody experiencing the same issue as I have? When using ZMM server version 3.0, iPhone devices with IOS 7.1 will not receive profiles. The only thing they do receive is one MDM profile. However, I expect at least 5 ZMM profiles on the iPhone device
-
Hi, I need to output data to a fixed length file. However, when i download the file and check the same on my local machine ..after writing 256 characters the file adapter is ignoring the rest of the data. Does any property need to be set in the adapt
-
2 sql statements in one trigger?
Greetings, I am working with the Oracle 10g Database. While creating several triggers I am encountering quite some problems. In fact, I want to do 2 steps in one trigger. Is that possible? e.g: Before Update on table for each row begin Update table s
-
Mail v7.2 - unable to email myself to inbox, goes to sent?
Fellow Applers! I upgraded to Mail v7.2 the other day - and now I cannot email myself to my inbox? The email I sent to myself goes to my 'Sent' folder - and then I have to drag it across to my Inbox. Is there a rule somewhere where Mail is automatica