FTPSClient, What values to give for Remote and Local - java

I am new to FTPSClient i trying to connect to a FTPS created in my laptop. i don't exactly what some of the methods working and their parameter meaning.
For example,
In my code i have created a FTPSClient as below:
FTPSClient ftps =new FTPSClient();
Then connected to a server use connect() method with ip address.
ftps.connect("172.xx.xx.xxx");
After every step i will check the reply code using.
ftps.getReplyCode();
In the below code i know that
username = system username
password = the password to login
ftps.login(username, password);
In the my system in Internet Information Service(IIS). Created an ftp server with ssl and given the below directory to share.
C:\Users\karan-pt2843\Desktop\FTPS
Want to send the file in below directory to the server.
D:\sam.txt
Now i want to store a file in the server in the given above directory and i tried using
remote="";
local="";
InputStream input;
input = new FileInputStream(local);
ftps.storeFile(remote, input);
input.close();
I don't know what value to give for remote and local. please help me with the values to give on them and the what happens internal.

// Use passive mode as default because most of us are
// behind firewalls these days.
ftps.enterLocalPassiveMode();
...
String remote = "samFromClient.txt"; //Place on FTP
String input = "D:/sam.txt" //Place on your Client
//Your FTP reads from the inputstream and store the file on remote-path
InputStream input = new InputStream(new FileInputStream(input));
ftps.storeFile(remote, input);
input.close();
ftps.logout();
...
Taken from: Apache example

Related

How to get server's SSH version without authenticating in JSch?

I tried to use JSch:
#Test
public void test() throws Exception {
var session = new JSch().getSession("host");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
var version = session.getServerVersion();
System.out.println("version = " + version);
}
but I'm getting
java.lang.NullPointerException: Cannot read the array length because "str" is null
It seems that this implementation requires you to connect and authenticate.
How can I get this information with Java, without the need to authenticate?
This Python code works for me on a server that requires authentication yet I didn't have to authenticate in order to get the remote version.
import paramiko
ssh = paramiko.Transport(("host", 22))
ssh.start_client()
print(ssh.remote_version)
ssh.close()
The SSH identification string is sent in plain text right after opening the connection.
So you do not need an SSH library to obtain the string.
You can do with a simple code like shown here:
Read Data from a Java Socket
Or just try to login using dummy credentials with JSch and then read Session.getServerVersion.
You do not even have to try to login. You can abort the connection right at the host key check:
config.put("StrictHostKeyChecking", "yes");

java interact with payshield 9000

Is it possible to build java application that can be used to verified
pin based on its pan, and change the pin if the customer need it. My company use thales payshield 9000..?
I can only connect through the hsm via ip and port
private String HSM_IP = "10.100.2.4";
private String HSM_PORT = "9998";
private Socket socket = null;
try{
socket = new Socket(HSM_IP,HSM_PORT);
socket.connect();
System.out.println("Connection Success");
}catch (IOException iex){
System.out.println("Connection Failed : " + iex.getMessage());
}
I don't have any idea how to validate the pin entered by the customer , and change the pin if customer need it. Please help me, or tell me what I need to know first....thank you. (I'm sorry for my bad english)
You could connect Thales HSM with Tcp and send commands to verify your PinBlock Data. HSM does not check nor understand your choice of language. You could check Thales documentation "Command Reference Manual" to inspect details.
There are different commands to verify your PIN data:
Verify a PIN Using the IBM Method
Verify a PIN Using the IBM Method
Verify a PIN Using the VISA PVV Method
Verify a PIN Using the VISA PVV Method
Verify a PIN Using the Diebold Method
Verify a Terminal PIN Using the Comparison Method
Verify an Interchange PIN Using the Comparison Method
Translate a PIN and PIN Length

Java application hanging during LIST command to FTP Server (Apache Commons FTPClient)

I'm currently trying to pull a file from an FTP server, but I've hit a snag in the process. The code below is a only partial working piece that:
logs into the FTP server
makes a few setting changes
attempts to list the files found in that directory.
The issue: When the LIST command is pushed to the FTP server, it just hangs without timing out, erroring out, or tossing an exception. I actually accidentally left this process running over the weekend and it hung at this point the entire time. I've included the reply strings output from the FTP server, but I feel like there is more specific error information that I'm missing that would help me pinpoint this error.
Questions:
Is there another method in the apache-commons-net FTPSClient list to output more specific error information from the FTP server? I looked through the JavaDocs for a method and didn't find anything specific - but I'm admittedly notorious for missing methods in JavaDocs (my vision is a bit bad...)
Could I be missing a simple configuration step in the process of connecting to the FTP server? I've checked all of my configuration against the login information sent to me. Here is a screenshot of the Site Manager with server information from Filezilla (note: I've removed the ftp hostname, this is correct in the code). EDIT: The server is set to listen to port 991.
Could I be dealing with a port issue? I'm hoping if this is the case, then request 1 would be able to give me more detail...
We've tried this code in three different environments - one remote an two local. Any help on this would be much appreciated as both myself and a more senior developer on my team are stumped. Thank you for your time!
Main method:
FTPSClient ftp = new FTPSClient();
boolean error = false;
try {
int reply;
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
ftp.connect("SITE_NAME", 991);
ftp.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("Set file type to binary");
ftp.sendCommand("PBSZ 0");
ftp.sendCommand("PROT P");
ftp.enterLocalPassiveMode();
System.out.println("Set mode to passive (local).");
//ftp.enterRemotePassiveMode();
//System.out.println("Set mode to passive.");
boolean success = ftp.login("USERNAME", "PASSWORD");
if (!success) {
System.out.println("Could not login to the server");
return;
} else {
System.out.println("LOGGED IN SERVER");
}
ftp.setBufferSize(1024 * 1024);
//ftp.sendCommand("OPTS UTF8 ON");
String directory = ftp.printWorkingDirectory();
System.out.println("Working directory: " + directory);
int timeout = ftp.getConnectTimeout();
System.out.println("Timeout Length: " + timeout);
FTPFile[] list = ftp.listFiles();
System.out.println("Generate List of Files");
int length = list.length;
System.out.println("Length: " + length);
ftp.logout();
} catch(IOException e) {
error = true;
e.printStackTrace();
} finally {
if(ftp.isConnected()) {
try {
ftp.disconnect();
} catch(IOException ioe) {
// do nothing
}
}
//System.exit(error ? 1 : 0);
}
}
Output from Protocol Command Listener:
220 Microsoft FTP Service
AUTH TLS
234 AUTH command ok. Expecting TLS Negotiation.
TYPE I
200 Type set to I.
Set file type to binary
PBSZ 0
200 PBSZ command successful.
PROT P
200 PROT command successful.
Set mode to passive (local).
USER *******
331 Password required
PASS *******
230 User logged in.
LOGGED IN SERVER
PWD
257 "/" is current directory.
Working directory: /
Timeout Length: 0
SYST
215 Windows_NT
PASV
227 Entering Passive Mode (204,179,168,88,195,91).
LIST
125 Data connection already open; Transfer starting.

Apache FTPClient - incomplete file retrieval on Linux, works on Windows

I have a java application on Websphere that is using Apache Commons FTPClient to retrieve files from a Windows server via FTP. When I deploy the application to Websphere running in a Windows environment, I am able to retrieve all of the files cleanly. However, when I deploy the same application to Webpshere on Linux, there are cases where I am getting an incomplete or corrupt files. These cases are consistent though, such that the same files will fail every time and give back the same number of bytes (usually just a few bytes less than what I should be getting). I would say that I can read approximately 95% of the files successfully on Linux.
Here's the relevant code...
ftpc = new FTPClient();
// set the timeout to 30 seconds
ftpc.enterLocalPassiveMode();
ftpc.setDefaultTimeout(30000);
ftpc.setDataTimeout(30000);
try
{
String ftpServer = CoreApplication.getProperty("ftp.server");
String ftpUserID = CoreApplication.getProperty("ftp.userid");
String ftpPassword = CoreApplication.getProperty("ftp.password");
log.debug("attempting to connect to ftp server = "+ftpServer);
log.debug("credentials = "+ftpUserID+"/"+ftpPassword);
ftpc.connect(ftpServer);
boolean login = ftpc.login(ftpUserID, ftpPassword);
if (login)
{
log.debug("Login success..."); }
else
{
log.error("Login failed - connecting to FTP server = "+ftpServer+", with credentials "+ftpUserID+"/"+ftpPassword);
throw new Exception("Login failed - connecting to FTP server = "+ftpServer+", with credentials "+ftpUserID+"/"+ftpPassword);
}
is = ftpc.retrieveFileStream(fileName);
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
IOUtils.copy(is, out);
} finally {
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(out);
}
byte[] bytes = out.toByteArray();
log.info("got bytes from input stream - byte[] size is "+ bytes.length);
Any assistance with this would be greatly appreciated.
Thanks.
I have a suspicion that the FTP might be using ASCII rather than binary transfer mode, and mapping what it thinks are Window end-of-line sequences in the files to Unix end-of-lines. For files that are really text, this will work. For files that are really binary, the result will be corruption and a slightly shorter file if the file contains certain sequences of bytes.
See FTPClient.setFileType(...).
FOLLOWUP
... so why this would work on Windows and not Linux remains a mystery for another day.
The mystery is easy to explain. You were FTP'ing files from a Windows machine to a Windows machine, so there was no need to change the end-of-line markers.

How to write java program to read new emails from any emailid

Hi I want to write a java program where I will provide my email id and password. and I want to read all new unread messages that arrived to that email id. I donot know how to write program for that.
The below program works fine for gmail. but it does not work for yahoomail because for yahoo pop3 is not configured. I want a generic code which will work for all email id.
import java.io.*;
import java.util.*;
import javax.mail.*;
public class ReadMail {
public static void main(String args[]) throws Exception {
// String host = "pop.gmail.com";
// String user = "xyz";
// String password = "12345";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
}
You need to know more than just login-pass. Things like mail server address, mail server type, port for connections, etc.
You should probably check out Java Mail API, or Commons Email.
UPD:
You create a Session using Session.getDefaultInstance() method (which takes connection Properties object and authenticator), get a Store from this Session using Session.getStore() method, get a Folder from that store using Store.getFolder("FOLDER_NAME") method, open that Folder, using Folder.open(Folder.READ) method, and get all messages, using something like Message[] messages = inboxFolder.getMessages();
Is that what you were looking for?
UPD2:
There is simply no way to write a generic program, which will work with any mail provider, using just server path, userID and password. Because different mail servers are configured differently. They talk differen protocols (imap/pop3/pop3 ssl) on different ports. There's always some guy, who has configured his mail server to talk imap over ssl on 31337 port only, all the other ports and protocols are banned. And this guy breaks your program. So, you'll have to specify all this properties in your properties object. Look here for properties, you'll have to specify.
UPD3:
On second thought, you actually have one option. Just try connecting to the server using different protocols. If that does not help, start iterating through ports. The one that fits is your configuration. If that's really what you want.
You need the javax.mail package, and the documentation of it. Read the documentation. Then you know.
There are two ways to do it:
1) Google provides API's to access mail you could use that library which provides more control over your mails. See here: http://code.google.com/apis/gmail/. In the same way try for other email providers.
2) Simple mail client(you could find it easily googling), but you need to look at headers to identify which mails are read/unread etc.
You need a registry where you can get the properties for a given mail service.
For instance, instead of specifying a pop3 host, you could specify the name of a .properties file that would contain the host, the port, the protocol, etc...
If your .properties file contains the protocol, for instance mail.store.protocol=pop3, you could use session.getStore() (with no argument), and the same code could be used for pop3, imap, pop3s, imaps.

Categories

Resources