I have a Java App that creates a local HTTP Webserver on Port 8080. Is there any possible Way how I can use/ install Php on it? I searched on google about this but couldnt find any help..... Any Help is appreciated!
My Code so far:
package minet;
import java.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
public class main {
private static ServerSocket serverSocket;
public static void main(String[] args) throws IOException {
JFrame ip = new JFrame();
JTextField field = new JTextField();
field.setText("http://" + getIP() + ":8080");
field.setEditable(false);
field.setBounds(10, 10, 380, 110);
ip.add(field);
JButton shutdown = new JButton("Shutdown Minet");
shutdown.setBounds(30, 120, 340, 50);
ip.add(shutdown);
ip.setLocationRelativeTo(null);
ip.setSize(400, 200);
ip.setLayout(null);
ip.setVisible(true);
shutdown.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Shutting down Minet...");
field.setText("Shutting down Minet...");
setTimeout(() -> System.exit(0), 1000);
}
});
serverSocket = new ServerSocket(8080); // Start, listen on port 8080
while (true) {
try {
Socket s = serverSocket.accept(); // Wait for a client to connect
new ClientHandler(s); // Handle the client in a separate thread
} catch (Exception x) {
System.out.println(x);
}
}
}
public static void setTimeout(Runnable runnable, int delay) {
new Thread(() -> {
try {
Thread.sleep(delay);
runnable.run();
} catch (Exception e) {
System.err.println(e);
}
}).start();
}
private static String getIP() {
// This try will give the Public IP Address of the Host.
try {
URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ipAddress = new String();
ipAddress = (in.readLine()).trim();
/*
* IF not connected to internet, then the above code will return one empty
* String, we can check it's length and if length is not greater than zero, then
* we can go for LAN IP or Local IP or PRIVATE IP
*/
if (!(ipAddress.length() > 0)) {
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
System.out.println("IP Address is : " + ipAddress);
return (ipAddress);
} catch (Exception e) {
// This try will give the Private IP of the Host.
try {
InetAddress ip = InetAddress.getLocalHost();
System.out.println((ip.getHostAddress()).trim());
return ((ip.getHostAddress()).trim());
} catch (Exception ex) {
return "ERROR";
}
}
}
}
// A ClientHandler reads an HTTP request and responds
class ClientHandler extends Thread {
private Socket socket; // The accepted socket from the Webserver
// Start the thread in the constructor
public ClientHandler(Socket s) {
socket = s;
start();
}
// Read the HTTP request, respond, and close the connection
public void run() {
try {
// Open connections to the socket
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));
// Read filename from first input line "GET /filename.html ..."
// or if not in this format, treat as a file not found.
String s = in.readLine();
System.out.println(s); // Log the request
// Attempt to serve the file. Catch FileNotFoundException and
// return an HTTP error "404 Not Found". Treat invalid requests
// the same way.
String filename = "";
StringTokenizer st = new StringTokenizer(s);
try {
// Parse the filename from the GET command
if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements())
filename = st.nextToken();
else
throw new FileNotFoundException(); // Bad request
// Append trailing "/" with "index.html"
if (filename.endsWith("/"))
filename += "index.html";
// Remove leading / from filename
while (filename.indexOf("/") == 0)
filename = filename.substring(1);
// Replace "/" with "\" in path for PC-based servers
filename = filename.replace('/', File.separator.charAt(0));
// Check for illegal characters to prevent access to superdirectories
if (filename.indexOf("..") >= 0 || filename.indexOf(':') >= 0 || filename.indexOf('|') >= 0)
throw new FileNotFoundException();
// If a directory is requested and the trailing / is missing,
// send the client an HTTP request to append it. (This is
// necessary for relative links to work correctly in the client).
if (new File(filename).isDirectory()) {
filename = filename.replace('\\', '/');
out.print("HTTP/1.0 301 Moved Permanently\r\n" + "Location: /" + filename + "/\r\n\r\n");
out.close();
return;
}
// Open the file (may throw FileNotFoundException)
InputStream f = new FileInputStream(filename);
// Determine the MIME type and print HTTP header
String mimeType = "text/plain";
if (filename.endsWith(".html") || filename.endsWith(".htm"))
mimeType = "text/html";
else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))
mimeType = "image/jpeg";
else if (filename.endsWith(".gif"))
mimeType = "image/gif";
else if (filename.endsWith(".class"))
mimeType = "application/octet-stream";
out.print("HTTP/1.0 200 OK\r\n" + "Content-type: " + mimeType + "\r\n\r\n");
// Send file contents to client, then close the connection
byte[] a = new byte[4096];
int n;
while ((n = f.read(a)) > 0)
out.write(a, 0, n);
out.close();
} catch (FileNotFoundException x) {
out.println("HTTP/1.0 404 Not Found\r\n" + "Content-type: text/html\r\n\r\n"
+ "<html><head></head><body>" + filename + " not found</body></html>\n");
out.close();
}
} catch (IOException x) {
System.out.println(x);
}
}
}
(Stackoverflow doesnt likes that many code... Thats why i have this external Link...)
From your question I understood that you used to use PHP as a web programing language. And you want to make an application in Java that shows some pages from PHP Web Server.
For this I think you need to include Built-in web server in your application. You just need to download it, uncompress it in your application path or wherever you want. You can find an INSTALL file in the directory. Install it as it shown, then start web server by:
$ cd path/to/built-in/php/web/server
$ php -S localhost:8000
Executing cmd commands is shown in this post. You may change port number as you want.
Another variant is you will need to include compressed Apache and PHP in your application installation package, then uncompress it, and edit config files programmatically, and after your application will be installed on some computer.
For showing pages from the PHP Web Server you just need to use WebView. An example of how to use it in Swing is shown here or you may use JavaFX directly without Swing if you want, because WebView is a part of JavaFX.
I cannot determine the exact problem you are facing. But, by the question, it seems that you wan to install a PHP server alongside your JAVA server.
This can be done easily, just select a different port number, while installing PHP. Any PHP server selects port 80 by default, so this in itself solves your problem. Just install any PHP server, it can be accessed via http://localhost, whereas your java server can be accessed via http://localhost:8080.
There has been a similar discussion here. Please check it out.
Related
My goal here is to make a simple HTTP proxy that can perform GET/POST requests, trying to learn about Java Sockets. Would be appreciated if anyone can point me in that direction.
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.io.*;
import java.net.*;
/**
* This class implements a simple single-threaded proxy server.
**/
public class SimpleProxyServer {
/** The main method parses arguments and passes them to runServer */
public static void main(String[] args) throws IOException {
try {
// Check the number of arguments
if (args.length != 3)
throw new IllegalArgumentException("Wrong number of arguments.");
// Get the command-line arguments: the host and port we are proxy for
// and the local port that we listen for connections on
String host = args[0];
int remoteport = Integer.parseInt(args[1]);
int localport = Integer.parseInt(args[2]);
// Print a start-up message
System.out.println("Starting proxy for " + host + ":" + remoteport +
" on port " + localport);
// And start running the server
runServer(host, remoteport, localport); // never returns
}
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java SimpleProxyServer " +
"<host> <remoteport> <localport>");
}
}
/**
* This method runs a single-threaded proxy server for
* host:remoteport on the specified local port. It never returns.
**/
public static void runServer(String host, int remoteport, int localport)
throws IOException {
// Create a ServerSocket to listen for connections with
ServerSocket ss = new ServerSocket(localport);
// Create buffers for client-to-server and server-to-client communication.
// We make one final so it can be used in an anonymous class below.
// Note the assumptions about the volume of traffic in each direction...
final byte[] request = new byte[1024];
byte[] reply = new byte[4096];
// This is a server that never returns, so enter an infinite loop.
while(true) {
// Variables to hold the sockets to the client and to the server.
Socket client = null, server = null;
try {
// Wait for a connection on the local port
client = ss.accept();
// Get client streams. Make them final so they can
// be used in the anonymous thread below.
final InputStream from_client = client.getInputStream();
final OutputStream to_client= client.getOutputStream();
// Make a connection to the real server
// If we cannot connect to the server, send an error to the
// client, disconnect, then continue waiting for another connection.
try { server = new Socket(host, remoteport); }
catch (IOException e) {
PrintWriter out = new PrintWriter(new OutputStreamWriter(to_client));
out.println("Proxy server cannot connect to " + host + ":" +
remoteport + ":\n" + e);
out.flush();
client.close();
continue;
}
// Get server streams.
final InputStream from_server = server.getInputStream();
final OutputStream to_server = server.getOutputStream();
// Make a thread to read the client's requests and pass them to the
// server. We have to use a separate thread because requests and
// responses may be asynchronous.
Thread t = new Thread() {
public void run() {
int bytes_read;
try {
while((bytes_read = from_client.read(request)) != -1) {
to_server.write(request, 0, bytes_read);
to_server.flush();
}
}
catch (IOException e) {}
// the client closed the connection to us, so close our
// connection to the server. This will also cause the
// server-to-client loop in the main thread exit.
try {to_server.close();} catch (IOException e) {}
}
};
// Start the client-to-server request thread running
t.start();
// Meanwhile, in the main thread, read the server's responses
// and pass them back to the client. This will be done in
// parallel with the client-to-server request thread above.
int bytes_read;
try {
while((bytes_read = from_server.read(reply)) != -1) {
to_client.write(reply, 0, bytes_read);
to_client.flush();
}
}
catch(IOException e) {}
// The server closed its connection to us, so close our
// connection to our client. This will make the other thread exit.
to_client.close();
}
catch (IOException e) { System.err.println(e); }
// Close the sockets no matter what happens each time through the loop.
finally {
try {
if (server != null) server.close();
if (client != null) client.close();
}
catch(IOException e) {}
}
}
}
}
Code obtained from http://examples.oreilly.com/jenut/SimpleProxyServer.java
I was wondering how I would be able to extract the HOSTNAME from the inputstream and use that information extracted to pass to the method below.
try { server = new Socket(host, remoteport); }
catch (IOException e) {
PrintWriter out = new PrintWriter(new OutputStreamWriter(to_client));
out.println("Proxy server cannot connect to " + host + ":" +
remoteport + ":\n" + e);
out.flush();
client.close();
continue;
}
I've tried creating a method that converts the InputStream into a String format but it seems to make the program get stuck after assigning it to the variable. (Tried something like this over here - Read/convert an InputStream to a String)
You can create a separate ByteArrayOutputStream to get the information from the InputStream.
...
final OutputStream to_client= client.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
...
And then in the while loop you can write to baos as well
...
while((bytes_read = from_server.read(reply)) != -1) {
to_client.write(reply, 0, bytes_read);
to_client.flush();
baos.write(reply, 0, bytes_read);
}
baos.flush();
...
And you can finally get the string from baos.
String requestString = new String(baos.toByteArray());
Then, you can search the Host header by doing this:
String[] headers = requestString.split("\n");
for (int i = 0; i < headers.length; i++) {
if (headers[i].startsWith("Host")) {
String[] hostHeader = headers[i].split(":");
if (hostHeader.length > 1) {
host = hostHeader[1];
}
}
}
I'm trying write my individual HTTP Server and I need a help .
What is the method of ServerSocket or Socket class can to invoke on the URL and brining it into a code.
For example, if I write following link <b>http://localhost:8080/coupon/add?name=coupon name</b> in browser, I would be want to get this link into my code.
Maybe who know how can I do this?
my simple code:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTPServer {
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
All your code does right now is set up a TCP server.
HTTP is a Layer 7 protocol.
Once you accept the connection from the client, HTTP can be used for communication over that TCP socket.
You'd have to parse the HTTP request that the client sends, and from that, you'd know the URL.
In your case, you said:
I write following link http://localhost:8080/coupon/add?name=coupon name in browser
Your browser will send an HTTP request like the following example:
GET /coupon/add?name=coupon+name HTTP/1.0
Host: localhost:8080
In reality, there will be more HTTP headers there, as well as a trailing \r\n, but for our sake, let's keep it simple.
Note that special characters like space are URL-encoded, however space is also encoded as + in the query string - it could be either + or %20 depending on the client.
Hopefully it's reasonably clear to you from this explanation how you get the URL from this HTTP request.
The only missing part from the actual full link is the http:// part. The distinction between HTTP and HTTPS is not part of the HTTP protocol - it's above the socket layer but below the HTTP protocol layer. If you had SSL sockets, you'd know that on the server side, and determine based on whether it was an SSL socket or a "plain" socket, whether it was http or https.
Hope that helps.
I improved for testing the startServer method for getting information.
I'm trying to include the data that comes from URL from any browsers to URI or URL class of JAVA.
This impossible ? Maybe who know how can I do this ?
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("SERVER SOCKET TESTS:");
System.out.println("getChannel: " + serverSocket.getChannel());
System.out.println("getInetAddress: " + serverSocket.getInetAddress());
System.out.println("getLocalPort: " + serverSocket.getLocalPort());
System.out.println("getLocalSocketAddress: " + serverSocket.getLocalSocketAddress());
System.out.println();
System.out.println("CLIENT SOCKET TESTS:");
System.out.println("getChannel: " + socket.getChannel());
System.out.println("getLocalAddress: " + socket.getLocalAddress());
System.out.println("getLocalPort: " + socket.getLocalPort());
System.out.println("getLocalSocketAddress: " + socket.getLocalSocketAddress());
System.out.println("getRemoteSocketAddress: " + socket.getRemoteSocketAddress());
System.out.println("getInetAddress: " + socket.getInetAddress());
System.out.println("getInputStream: " + socket.getInputStream());
System.out.println("getOutputStream: " + socket.getOutputStream());
System.out.println();
System.out.println("URI - GET INFORMATION:");
URI uri = new URI("httpscheme://world.hello.com/thismy?parameter=value");
System.out.println(uri.getHost());
System.out.println(uri.getPath());
System.out.println(uri.getQuery());
System.out.println(uri.getScheme());
}
} catch (Exception e) {
System.out.println("error");
}
}
little test:
when I run code and after that open the browser and I write in my browser, for example: http://localhost:8080 I get information, but I don't understand following:
why the serverSocket object in getInetAddress method (serverSocket.getInetAddress) have an IP4 and it 0.0.0.0 (why not a standard local ip that defined on my computer) and the socket object of getInetAddress method (socket.getInetAddress) have an IP6 and it 0:0:0:0:0:0:0:1 . How can I get a standard host name localhost how to get the URI class (with chunks of data of link)?
The port is gated nice: 8080.
The problem for getting URL path , solved.
package pk6HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Morris on 08/10/16.
*/
public class HTTPServer {
private static String headerData;
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
boolean isClosed = false;
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
try {
try (InputStream raw = socket.getInputStream()) { // ARM
System.out.println("=================BEFORE STARTING READING HEADER =======================");
System.out.println("Collecting data to string array...");
headerData = getHeaderToArray(raw);
//
System.out.println("+++++++++++++++++ AFTER ENDING READING HEADER +++++++++++++++++++++++");
System.out.println("Hello World");
}
} catch (MalformedURLException ex) {
System.err.println(socket.getLocalAddress() + " is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
} catch (Exception ex) {
System.out.println("error# " + ex.getMessage());
}
}
public static String getHeaderToArray(InputStream inputStream) {
String headerTempData = "";
// chain the InputStream to a Reader
Reader reader = new InputStreamReader(inputStream);
try {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
headerTempData += (char) c;
if (headerTempData.contains("\r\n\r\n"))
break;
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
headerData = headerTempData;
return headerTempData;
}
}
We are deploying a Java project on Linux Server. A file is generated by the project which is then sent to a remote server.
It was earlier implemented using Jsch. However, due to its dependency on JCE and the inability to upgrade the java version (from 5) we are switching to Ganymed. I am using Ganymed build 210 (viz. is tested for java 5; http://www.ganymed.ethz.ch/ssh2)
This is the function I am using to sftp the file.
public boolean sftp_put() {
File privateKeyFile = new File(identityPath);
File rfile = new File(hostDir);
File lfile = new File(lpath);
boolean success = false;
try {
if (!lfile.exists() || lfile.isDirectory()) {
throw new IOException("Local file must be a regular file: "
+ lpath);
}
Connection ssh = new Connection(host, port);
ssh.connect();
ssh.authenticateWithPublicKey(user, privateKeyFile, password);
SFTPv3Client sftp = new SFTPv3Client(ssh);
try {
SFTPv3FileAttributes attr = sftp.lstat(hostDir);
if (attr.isDirectory()) {
rfile = new File(hostDir, lfile.getName());
}
} catch (SFTPException e) {
try {
SFTPv3FileAttributes attr = sftp.lstat(rfile.getParent());
if (!attr.isDirectory()) {
throw new IOException(
"Remote file's parent must be a directory: "
+ hostDir + "," + e);
}
} catch (SFTPException ex) {
throw new IOException(
"Remote file's parent directory must exist: "
+ hostDir + "," + ex);
}
}
SFTPv3FileHandle file = sftp.createFileTruncate(rfile
.getCanonicalPath());
long fileOffset = 0;
byte[] src = new byte[32768];
int i = 0;
FileInputStream input = new FileInputStream(lfile);
while ((i = input.read(src)) != -1) {
sftp.write(file, fileOffset, src, 0, i);
fileOffset += i;
}
input.close();
sftp.closeFile(file);
sftp.close();
success=true;
} catch (IOException e1) {
logger.warn("Exception while trying to sftp", e)
}
return success;
}
I am unable to connect to the remote server possibly due to binding issues and unsure on how to proceed? I am thinking on binding a local address before the SFTP.
So I wrote a socket function.
public Socket createSocket(String destinationHost, int destinationPort)
throws IOException, UnknownHostException {
logger.info("sftp configured bind address : " + bindAddress
+ ", bind port : " + bindPort);
Socket socket = new Socket();
socket.bind(new InetSocketAddress(bindAddress, bindPort));
socket.connect(new InetSocketAddress(destinationHost, destinationPort),
connectionTimeOut);
if (socket.isBound()) {
logger.info("sftp actual bind port : " + socket.getLocalPort());
} else {
logger.warn("sftp socket not bound to local port");
}
return socket;
}
However this is also not working, and I am getting a Socket Exception.
EDIT: So I was creating the socket in the right way but no where am I using the same socket for creating the connection. Such a method is not defined in any of the Ganymed libraries.
Since there was not an inherent method in ganymed, I edited the source code to write a method.
Following are the edits I made.
to the class where I am using
SocketAddress sourceAddress = new InetSocketAddress(bindAddress,
bindPort);
Connection ssh = new Connection(host, port);
ssh.bindSourceAddress(sourceAddress);
ssh.connect();
then I made some changes to connection.class of Ganymed API. Imported class and declared variables accordingly
This is the simple method for passing the bindAddress.
public void bindSourceAddress(SocketAddress sourceAddress) {
this.sourceAddress = sourceAddress;
}
Passing the address to Transport Manager class when initialize method is used.
if (sourceAddress != null) {
tm.initialize(cryptoWishList, verifier, dhgexpara,
connectTimeout, getOrCreateSecureRND(), proxyData,
sourceAddress);
} else {
tm.initialize(cryptoWishList, verifier, dhgexpara,
connectTimeout, getOrCreateSecureRND(), proxyData);
}
Modified the constructor of initialize method. It in turn calls an establish connection function, which is similarly modified to accomodate SocketAddress.
private void establishConnection(ProxyData proxyData, int connectTimeout, SocketAddress sourceAddress) throws IOException
{
/* See the comment for createInetAddress() */
if (proxyData == null)
{
InetAddress addr = createInetAddress(hostname);
//test
if (sourceAddress != null) {
sock.bind(sourceAddress);
}
sock.connect(new InetSocketAddress(addr, port), connectTimeout);
sock.setSoTimeout(0);
return;
}
if (proxyData instanceof HTTPProxyData)
{
HTTPProxyData pd = (HTTPProxyData) proxyData;
/* At the moment, we only support HTTP proxies */
InetAddress addr = createInetAddress(pd.proxyHost);
//test
if (sourceAddress != null) {
sock.bind(sourceAddress);
}
sock.connect(new InetSocketAddress(addr, pd.proxyPort), connectTimeout);
sock.setSoTimeout(0);
Finally bound the socket. Being a java Novice it took me my own sweet time to get this right. No one will most probably read this or need it, but posted this solution just in case for someone like me!
I've created Java function that downloads files from FTP server. It works fine from my local machine. But I need to run it under linux server (means another host and port). And the function gives an error
The collection, array, map, iterator, or enumeration portion of a for statement cannot be null
Caused in a line with the code:
for(String f : ftpNames) {
ftpclient.retrieveFile(f, os); // os is OutputStream
}
So it doesn't see the files...
I added
ftpclient.enterRemotePassiveMode();
And ftpclient.getPassiveHost() returns 227 Entering Passive Mode (x,x,x,x,204,15)
Tried to list and download them via shell - it works.
How should I modify my code to solve the problem? Thanks.
UPD. I got log from FTP server I'm trying to get files from, and there is such string:
425 Cannot open data connection
Full code:
static boolean ftpFilesDownload(String ip, int port, String login, String passwd, String ftpdir, String localdir) throws IOException {
Boolean result = false;
FTPClient client = new FTPClient();
String separator = File.separator;
try {
client.connect(ip, port);
System.out.println(client.getReplyString());
client.login(login, passwd);
System.out.println(client.getReplyString());
client.setControlKeepAliveTimeout(1000*60*5);
client.setControlKeepAliveReplyTimeout(1000*60*5);
client.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("client setFileType success");
client.changeWorkingDirectory(ftpdir);
System.out.println(client.getReplyString());
client.printWorkingDirectory();
System.out.println("directory changed");
FTPFile[] ftpFiles = client.listFiles();
System.out.println(ftpFiles);
String[] ftpNames = client.listNames();
System.out.println("the files are " + Arrays.toString(ftpNames)); // so null here...
for(String f : ftpNames) {
String localfile = localdir + f;
OutputStream os = new FileOutputStream(localfile);
try {
result = client.retrieveFile(f, os);
System.out.println("DOWNLOADING STARTED);
System.out.println(client.getReplyString());
client.noop();
}
catch(Exception e) {
System.out.println(e);
result = false;
}
finally {
if(os != null)
os.close();
}
}
client.logout();
System.out.println(client.getReplyString());
}
catch(Exception e)
{
System.out.println(e);
result = false;
}
finally
{
try
{
client.disconnect();
}
catch(Exception e)
{
System.out.println(e);
result = false;
}
}
return result;
}
As the error message explains, you're trying to iterate over a null object. You should check for this (or make sure an empty Iterable is used perhaps)
If this is an execptional (error) state, I'd check for this explicitly and throw some kind of runtime exception, e.g.:
if (ftpNames == null) {
throw new IllegalArgumentException("Cannot use a null set of FTP servers");
}
for (String f : ftpNames) {
ftpclient.retrieveFile(f, os); // os is OutputStream
}
Alternatively you could try to continue with no FTP servers, but seems a bit pointless.
Try to use ftpclient.enterLocalActiveMode();
I have a jsp web application hosted on a machine hosted in localhost.
I can access this web application from another machine on LAN.
What I'm doing here is I created a bean class which has a method that returns a IP of machine that access web app.
But when i was accessing from another machine I got the IP of hosted machine itself .
Can anyone tell why it happens? Tell me how can I get the IP of another machine that accesses web app hosted in local host.
You can try
getRemoteAddr
method of ServletRequest. Refer to Documentation for more details.
You can't reliably do so, but if you can control the network between all clients and servers, and if you're willing to accept that malicious requests may feed you false information, then there are methods available like ServletRequest.getRemoteAddr() that will give you information of that sort. To reiterate, it's by no means guaranteed to be the address of the machine that originally sent the request, and it's also guaranteed to be authentic in any way. Given the right (or wrong?) network conditions, it's easy to spoof that piece of information.
this is using a web service to get you the IP address
take a look
package ipInfo;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class ExternalIp {
private static String URL = "http://api-sth01.exip.org/?call=ip";
public static void main(String[] args) {
ExternalIp ipGetter = new ExternalIp();
ipGetter.getExternalIp();
}
public void getExternalIp()
{
BufferedReader reader = null;
String line = "";
int tries = 0;
do {
try {
reader = read(URL);
/*while(reader.readLine() != null)
{
line = line + reader.readLine();
}*/
line = reader.readLine();
}
catch (FileNotFoundException fne) {
System.out.println("File not found for url: " + URL);
System.out.println("Check your typing");
System.out.println();
return;
}
catch (IOException ioe) {
System.out.println("Got IO Exception, tries = " + (tries + 1));
System.out.println("Message: " + ioe.getMessage());
tries++;
try {
Thread.currentThread().sleep(300000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
continue;
}
catch (Exception exc) {
exc.printStackTrace();
}
} while (reader == null && tries < 5);
if (line != null && line.length() > 0) {
System.out.println("Your external ip address is: " + line);
}
else {
System.out.println("Sorry, couldn't get your ip address");
}
}
public BufferedReader read(String url) throws Exception{
return new BufferedReader(
new InputStreamReader(
new URL(url).openStream()));
}
}